Linux 使用 awk 替换正则表达式模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14432209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:44:43  来源:igfitidea点击:

Substitute a regex pattern using awk

regexlinuxawk

提问by Ajay Nair

I am trying to write a regex expression to replace one or more '+' symbols present in a file with a space. I tried the following:

我正在尝试编写一个正则表达式来用空格替换文件中存在的一个或多个“+”符号。我尝试了以下方法:

 echo This++++this+++is+not++done | awk '{ sub(/\++/, " "); print }'
 This this+++is+not++done

Expected:

预期的:

This this is not done

Any ideas why this did not work?

任何想法为什么这不起作用?

采纳答案by Guru

Use gsubwhich does global substitution:

使用gsubwhich 进行全局替换:

echo This++++this+++is+not++done | awk '{gsub(/\++/," ");}1'

subfunction replaces only 1st match, to replace all matches use gsub.

sub函数仅替换第一个匹配项,要替换所有匹配项,请使用gsub.

回答by alex

You could use sedtoo.

你也可以用sed

echo This++++this+++is+not++done | sed -e 's/+\{1,\}/ /g'

This matches one or more +and replaces it with a space.

这匹配一个或多个+并用空格替换它。

回答by radical7

Or the trcommand:

或者tr命令:

echo This++++this+++is+not++done | tr -s '+' ' '

回答by Mirage

Try this

尝试这个

echo "This++++this+++is+not++done" | sed -re 's/(\+)+/ /g'

echo "This++++this+++is+not++done" | sed -re 's/(\+)+/ /g'

回答by Ed Morton

The idiomatic awk solution would be just to translate the input field separator to the output separator:

惯用的 awk 解决方案只是将输入字段分隔符转换为输出分隔符:

$ echo This++++this+++is+not++done | awk -F'++' '{=}1'
This this is not done

回答by dsri

echo "This++++this+++is+not++done" | sed 's/++*/ /g'

回答by mathiasrw

If you have access to node on your computer you can do it by installing rexreplace

如果您可以访问计算机上的节点,则可以通过安装 rexreplace 来实现

npm install -g regreplace

and then run

然后运行

rexreplace '\++' ' ' myfile.txt

Of if you have more files in a dir datayou can do

如果你在一个目录中有更多的文件,data你可以做

rexreplace '\++' ' ' data/*.txt