使用sed和grep来搜索和替换 [英] Using sed and grep to search and replace
问题描述
我正在使用 egrep -R
,然后是包含大约10个联合的正则表达式,如下所示:
.jpg | .png | .gif
等。这很好,现在我想用 .bmp
$ b替换所有找到的字符串$ b
我正在考虑类似于
egrep -lR\.jpg | \.png | \\ \\.gif。 | seds / some_expression / .jpg /file_it_came_form
所以这里的问题是如何做一个类似的联合正则表达式在 sed
中,我如何告诉它将变化保存到获得输入的文件中。
使用此命令:
egrep -lRZ\.jpg | \.png | \.gif。 \
| xargs -0 -l sed -i -e's / \.jpg \ | \.gif \ | \.png / .bmp / g'
-
egrep
:找到匹配使用扩展正则表达式的行
-
-l </ code>:只列出匹配的文件名
-R
:通过所有给定目录递归搜索 -
-Z
:使用\ 0
作为记录分隔符 -
\.jpg | \.png | \.gif
:匹配其中一个字符串。jpg
,.gif
或。png
$ b -
xargs
:以stdin为参数执行命令
-
-0
:use\ 0
作为记录分隔符。这对匹配egrep
中的-Z
很重要,以避免被输入文件名中的空格和换行符所迷惑。 / b> -
-l </ code>:每条命令使用一行作为参数
$ b
sed
: s tream ed itor
-
-i
:使用输出替换输入文件而不进行备份
's / \.jpg \ | \.gif \ | \.png /。 bmp / g'
:替换所有出现的字符串。jpg
,。gif
或。png
与。bmp
I am using egrep -R
followed by a regular expression containing about 10 unions, so like:
.jpg | .png | .gif
etc. This works well, now I would like to replace all strings found with .bmp
I was thinking of something like
egrep -lR "\.jpg|\.png|\.gif" . | sed "s/some_expression/.jpg/" file_it_came_form
so the issue here is how do I do a similar union regular expression in sed
and how do I tell it to save the changes to the file that it got the input from.
Use this command:
egrep -lRZ "\.jpg|\.png|\.gif" . \
| xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
egrep
: find matching lines using extended regular expressions-l
: only list matching filenames-R
: search recursively through all given directories-Z
: use\0
as record separator"\.jpg|\.png|\.gif"
: match one of the strings".jpg"
,".gif"
or".png"
.
: start the search in the current directory
xargs
: execute a command with the stdin as argument-0
: use\0
as record separator. This is important to match the-Z
ofegrep
and to avoid being fooled by spaces and newlines in input filenames.-l
: use one line per command as parameter
sed
: the stream editor-i
: replace the input file with the output without making a backup-e
: use the following argument as expression's/\.jpg\|\.gif\|\.png/.bmp/g'
: replace all occurrences of the strings".jpg"
,".gif"
or".png"
with".bmp"
这篇关于使用sed和grep来搜索和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!