我正在使用grep解析一个文件,屏幕上的输出包含换行符,如下所示:
$ grep 'gene' sequence.gb
gene 89..1483
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
gene complement(1987..2763)
/gene="nucleocapsid protein"
/gene="nucleocapsid protein"我可以将它赋值给一个变量,然后用换行符打印出来:
$ gene=$(grep 'gene' sequence.gb)
echo "$gene"
gene 89..1483
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
gene complement(1987..2763)
/gene="nucleocapsid protein"
/gene="nucleocapsid protein"但这并不包含真正的换行符,因为如果我再次对包含“..”的行进行grep操作我得到了很多:
$ echo "$gene" | grep '..'
gene 89..1483
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
gene complement(1987..2763)
/gene="nucleocapsid protein"
/gene="nucleocapsid protein"通过不使用引号,我们可以看到这是一个字符串:
$ echo $gene
gene 89..1483 /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" gene complement(1987..2763) /gene="nucleocapsid protein" /gene="nucleocapsid protein"因此,我的问题是,我如何保持换行符格式或引入它?
谢谢
发布于 2018-05-22 17:59:18
因为.是正则表达式通配符,所以grep '..'匹配至少有两个字符的每一行:
$ echo "$gene" | grep '..'
gene 89..1483
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
gene complement(1987..2763)
/gene="nucleocapsid protein"
/gene="nucleocapsid protein"在正则表达式中,.是非常疯狂的:它不仅会匹配任何字母或数字,还会匹配任何标点符号、空白、制表符或任何其他字符。
若要只匹配句点,请使用-F:
$ echo "$gene" | grep -F '..'
gene 89..1483
gene complement(1987..2763)-F是--fixed-strings的缩写,并告诉grep将模式视为固定字符串,而不是正则表达式。
或者,您可以转义句点,以便它们只匹配句点(帽子提示:尼克):
$ echo "$gene" | grep '\.\.'
gene 89..1483
gene complement(1987..2763)否则,我们可以强制grep将句点作为文字句点来处理,方法是将它们放入字符类(帽子提示:戴夫_汤普森):
$ echo "$gene" | grep '[.][.]'
gene 89..1483
gene complement(1987..2763)但是,如果不需要正则表达式,请使用-F,因为它使grep处理速度快得多。
https://unix.stackexchange.com/questions/445397
复制相似问题