bash 匹配空格字符正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10740051/
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
matching space character regex
提问by mawia
Well I have few files with series of contents in following format:
好吧,我有几个包含以下格式内容系列的文件:
[abc] #4 *5
[pqr] #3 *4
[xyx] #5 *2
Now I needed to replace all occurance of
现在我需要替换所有出现的
[xyx] #3 *2
by
经过
[xyx] #1 *2
in all the files.
在所有文件中。
Now the question which is causing pain is the presence of space between [xyz] and #3. There are two thing I'm taking this search expression as command line argument in a script which looks like this:
现在引起疼痛的问题是 [xyz] 和 #3 之间是否存在空间。我将此搜索表达式作为命令行参数用于脚本中的两件事,如下所示:
searchExp=
repalaceExp=
echo $searchExp
echo $replaceExp
for i in `grep \'$searchExp\'`
do
sed 's/$searchExp/$replaceExp' $i > $i.new
done
I guess this should be fine given that I'm passing argument as:
我想这应该没问题,因为我将参数传递为:
./replace_script '^\[xyz\] #3' '\[xyz\] #1'
Now as you see the echo statment int the script reduces all the spaces in the search and relace expression to a single space
现在,当您看到 echo 语句 int 时,脚本将搜索和重新定位表达式中的所有空格减少到一个空格
\[xyz\] #3
Now I tried few other alternative to take care of space character
现在我尝试了其他一些替代方法来处理空格字符
1. ^\[xyz\][ ]+#3
This is one is screaming that unbalanced [ ],so regex error
这是一个尖叫不平衡的[],所以正则表达式错误
2. ^\[xyz\]\s+#3 //as per few suggestion on SO
This does'nt matches.
这不匹配。
Can you see where I'm going wrong?
你能看出我哪里错了吗?
Edit:Corrected Typo
编辑:更正错别字
回答by jlliagre
A better way would be to use a regular expression with a back reference like this:
更好的方法是使用带有反向引用的正则表达式,如下所示:
searchExp='\(\[xyx\][[:space:]]*\)#5'
replaceExp='#1'
sed "s/$searchExp/$replaceExp/" <<%EOF%
[abc] #4 *5
[pqr] #3 *4
[xyx] #5 *2
%EOF%
[abc] #4 *5
[pqr] #3 *4
[xyx] #1 *2
Note too that you need double quotes for variables to be expanded.
还要注意,要扩展的变量需要双引号。
回答by Shahbaz
echoalways reduces spaces so don't count on its output.
echo总是减少空间,所以不要指望它的输出。
What you are really missing is that this:
你真正缺少的是:
sed 's/searchExp/replaceExp' $i > $i.new
should in fact be
事实上应该是
sed "s/$searchExp/$replaceExp/" $i > $i.new
If you want to make sure you actually matched the lines, you can write the echo(or better, printf) inside the forloop.
如果你想确保你真的匹配了这些行,你可以在循环中写下echo(或更好的printf)for。
Finally, if you want to use sedon all files and replace in-place, you can write like this:
最后,如果你想sed在所有文件上使用并替换in-place,你可以这样写:
searchExp=
repalaceExp=
sed -i "s/$searchExp/$replaceExp/" *

