问题描述
在文件 test.py
中,其内容为:
#!/usr/bin/env python导入操作系统导入球对于glob.glob('*.txt')中的f:打印f
...我想以编程方式替换:
glob.glob('*.txt')
...和:
glob.glob('*.txt')+ glob.glob('*.dat')
使用 sed
.
我尝试过:
sed -i"s,glob.glob('*.txt'),glob.glob('*.txt')+ glob.glob('*.dat'),g" test.py
...但是,这不会替换字符串.我有一种预感,这与在字符串中使用单引号来替换和/或解释外壳本身(bash)中的各种引号有关.怎么了?
您需要在搜索模式中转义所有特殊的正则表达式元字符,例如.
或 *
./p>
您可以在 sed
命令中使用双引号.还要使用&
进行替换,以避免再次重复匹配的文本.
sed"s/glob \ .glob('\ * \.txt')/& + glob.glob('*.dat')/" test.py#!/usr/bin/env python导入操作系统导入球对于glob.glob('*.txt')+ glob.glob('*.dat')中的f:打印f
In a file test.py
which reads:
#!/usr/bin/env python
import os
import glob
for f in glob.glob('*.txt'):
print f
...I'd like to programatically replace:
glob.glob('*.txt')
... with:
glob.glob('*.txt')+glob.glob('*.dat')
using sed
.
I have tried:
sed -i "s,glob.glob('*.txt'),glob.glob('*.txt')+glob.glob('*.dat'),g" test.py
...however this does not replace the string. I have a hunch that this has to do with the use of single quotes in the string to replace and/or the interpretation of the various quotation marks in the shell itself (bash). What is going wrong?
You need to escape all special regex meta characters such as .
or *
in search pattern.
You can use double quotes in sed
command. Also use &
in replacement to avoid repeating matched text again.
sed "s/glob\.glob('\*\.txt')/&+glob.glob('*.dat')/" test.py
#!/usr/bin/env python
import os
import glob
for f in glob.glob('*.txt')+glob.glob('*.dat'):
print f
这篇关于在sed中转义单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!