Awk:使用反向匹配到字符串,然后替换字符 [英] Awk: Using invert match to a string and then substitute characters

查看:731
本文介绍了Awk:使用反向匹配到字符串,然后替换字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要提取不包含#的行,并在输出中删除";.

I want to extract lines that don't contain # and delete ", ; in the output.

我的输入文件如下:

# ;string"1"
# string"2"; 
string"3";

可以使用greptr获得所需的输出:

Can use grep and tr to get wanted output:

grep -v '#' FILE | tr -d ';"'  
string3

但是我想使用awk.

我可以提取反转匹配awk '!/#/' FILE,但是如何使用sub在同一awk命令中删除";?

I can extract invert match awk '!/#/' FILE, but how can I use sub to delete ", ; in the same awk command?

推荐答案

您可以使用gsub进行全局替换:

You can use gsub for global substitution:

awk '!/#/{gsub(/[";]/,"",$0);print}'

下面的记录显示了这一操作,它提供的结果与您的grep/tr管道相同:

The following transcript shows this in action, it delivers the same results as your grep/tr pipeline:

pax> echo '# ;string"1"
# string"2"; 
string"3";' | awk '!/#/{gsub(/[";]/,"",$0);print}{}'

string3

请注意,在awk的某些实现中,最终的{}可能不是必需的,但是在那些不自动匹配的实现中(通常是较旧的)中,它会停止输出不匹配的行.规则.

Note that the final {} may not be necessary in some implementations of awk but it's there to stop output of non-matching lines in those implementations (usually older ones) that do it automatically for lines matching none of the rules.

这篇关于Awk:使用反向匹配到字符串,然后替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆