搜索和使用常规的前pressions在bash取代 [英] Search and replace in bash using regular expressions
问题描述
我已经看到了这个例子:
I've seen this example:
hello=ho02123ware38384you443d34o3434ingtod38384day
echo ${hello//[0-9]/}
这语法如下: $ {//可变模式/换货}
不幸的是,模式
字段似乎并不支持完整的regex语法(如果我使用。
或 \\ S
,例如,它尝试匹配文字字符)。
Unfortunately the pattern
field doesn't seem to support full regex syntax (if I use .
or \s
, for example, it tries to match the literal characters).
我如何搜索/使用完整的regex语法替换字符串?
How can I search/replace a string using full regex syntax?
推荐答案
使用 SED :
MYVAR=ho02123ware38384you443d34o3434ingtod38384day
echo $MYVAR | sed -e 's/[a-zA-Z]/X/g' -e 's/[0-9]/N/g'
# prints XXNNNNNXXXXNNNNNXXXNNNXNNXNNNNXXXXXXNNNNNXXX
请注意,随后的 -e
的才能进行处理。此外,对于前pression的先按g
标志将匹配输入所有事件。
Note that the subsequent -e
's are processed in order. Also, the g
flag for the expression will match all occurrences in the input.
您也可以使用这种方法,即Perl中,awk中,例如挑自己喜欢的工具:
You can also pick your favorite tool using this method, i.e. perl, awk, e.g.:
echo $MYVAR | perl -pe 's/[a-zA-Z]/X/g and s/[0-9]/N/g'
这可以让你做更多的创意匹配...例如,在上面的剪断,数字更换不会,除非是在第一八佰伴pression比赛(由于懒惰<$ C使用$ C>和评估)。当然,你有完整的语言支持的Perl听从你的命令......
This may allow you to do more creative matches... For example, in the snip above, the numeric replacement would not be used unless there was a match on the first expression (due to lazy and
evaluation). And of course, you have the full language support of Perl to do your bidding...
这篇关于搜索和使用常规的前pressions在bash取代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!