如何使用 grep 删除以“chr1”开头的条目,但保留那些以“chr11”或“chr19”开头的条目?

use*_*234 1 grep regular-expression

我有一个包含以下条目的文件:

chr1    740678  740720
chr1    2917480 2917507
Run Code Online (Sandbox Code Playgroud)

我想删除以开头的条目chr1但保留其他以chr11or开头的条目,chr19依此类推。当我使用grep -v "chr1"它时,它会删除以 chr11 或 chr19 开头的其他内容。我可以使用其他正则表达式吗?

ter*_*don 5

首先,您应该将正则表达式锚定为仅匹配行 ( ^chr1)的开头,以避免查找包含chr1但不是第一个字符串的行(例如,对于带注释的 VCF 文件,这很容易发生)。接下来,您可以使用-w(GNU)的选项grep

   -w, --word-regexp
          Select  only  those  lines  containing matches that
          form whole words.  The test is  that  the  matching
          substring  must  either  be at the beginning of the
          line,  or  preceded  by  a   non-word   constituent
          character.  Similarly, it must be either at the end
          of the line or followed by a  non-word  constituent
          character.     Word-constituent    characters   are
          letters, digits, and the underscore.   This  option
          has no effect if -x is also specified.
Run Code Online (Sandbox Code Playgroud)

如果你grep不支持,那么使用这个:

grep -v '^chr1\s' file
Run Code Online (Sandbox Code Playgroud)

\s场比赛的空白(包括空格和制表符),这样就排除与启动任何行chr1,然后任何空白字符的。