awk - 如果 $2 包含字符串则删除行

awk - 如果 $2 包含字符串则删除行

如果 $2 包含字符串,我想删除整行,

字符串示例 =“hello123”

输入示例:

Hey:hello123
Hey:hello

预期输出:

Hey:hello

答案1

<input.txt awk -F: '$2 !~ "hello123"' >output.txt

设置:为字段分隔符,打印第二列不包含的所有行hello123


如果这将成为脚本的一部分,则将 shell 变量与您的搜索模式一起传递给 awk 可能会有所帮助:

var='hello123'
awk -F: -v pattern="$var" '$2 !~ pattern' input.txt > output.txt

答案2

Command

First method

sed -n -i '/^Hey:hello123$/!p'  filename


output

cat filename
Hey:hello


second method

python

#!/usr/bin/python

    import re
    k=open('l.txt','r')
    u=open('o.txt','w')
    for i in k:
        if "Hey:hello123" not in i:
            u.write(i)

output
cat o.txt 
Hey:hello


Third method

 awk -F ":" '$2 != "hello123" {print $0}' filename

    If you want to replace in orginal file use below method

    awk -F ":" '$2 != "hello123" {print $0}' l.txt >temperory && mv temperory filename


    output

    Hey:hello

相关内容