sed 删除带有图案且以奇数结尾的线条

sed to remove lines with pattern and that end in odd digit

提问人:justaguy 提问时间:10/10/2023 最后编辑:Timur Shtatlandjustaguy 更新时间:10/11/2023 访问量:88

问:

在下面,我试图删除所有以奇数结尾的行。这两个命令都执行,但返回的文件保持不变。sedID_

文件

ID_0111 xxx
ID_0112 xxx
ID_0113 xxx
ID_0114 xxx
xxxxxxxxxxxxxxxx

期望

ID_0112 xxx
ID_0114 xxx
xxxxxxxxxxxxxxxx

赛德

sed '/ID_[13579]/d' file.txt
sed 's|ID_[13579]$| |g'
正则表达式 SED

评论

1赞 Mark Setchell 10/11/2023
如果要就地编辑原始文件,则需要添加。-i

答:

3赞 anubhava 10/11/2023 #1

您可以使用以下方法:sed

sed '/^ID_[^ ]*[13579] /d' file

ID_0112 xxx
ID_0114 xxx
xxxxxxxxxxxxxxxx

在这里,正则表达式模式匹配以 开头的行,后跟 0 个或多个非空格字符,并在匹配空格之前结束。/^ID_[^ ]*[13579] /ID_[13579]

否则,使用 you 可以这样做:awk

awk '$1 !~ /^ID_/ || $1 ~ /[02468]$/' file

ID_0112 xxx
ID_0114 xxx
xxxxxxxxxxxxxxxx
3赞 choroba 10/11/2023 #2

奇数前可以有任意数字,奇数后面必须有一个空格。

sed '/ID_[0-9]*[13579] /d'
1赞 Timur Shtatland 10/11/2023 #3

你可以像这样使用 GNU grep

grep -P -v '^ID_\d*[13579]\s' in_file > out_file

这里,使用以下选项: :
使用 Perl 正则表达式。
:打印匹配的行。
grep-P-v

正则表达式具有:

^:匹配行的开头。
:0 位或更多位数字。
:任意奇数。
:空白。
\d*[13579]\s

1赞 Ed Morton 10/11/2023 #4

使用任何 awk:

$ awk -F_ '!(/^ID_/ && $2%2)' file
ID_0112 xxx
ID_0114 xxx
xxxxxxxxxxxxxxxx