[英]Replace string using grep and sed
I have bunch of files in a directory, I need to change prefix of lines in file like "AB_" to "YZ_" how can i do it? 我在目录中有一堆文件,我需要将“ AB_”之类的文件中的行前缀更改为“ YZ_”,我该怎么办?
i have used grep and sed like, 我用过grep和sed,
grep -nr "AB_" ./ | xargs -0 sed -i 's/AB_/YZ_/g'
but giving error, : File name too long
但出现错误: File name too long
example string in a file are: Hello AB_WORLD!
文件中的示例字符串是: Hello AB_WORLD!
and Hello WORLD_AB!
和Hello WORLD_AB!
Thanks. 谢谢。
You mean grep -lr
not grep -nr
您的意思是grep -lr
而不是grep -nr
grep -lr
-l
gives you the file name; -l
为您提供文件名; -n
gives you the matching line with line number prepended -n
为您提供匹配的行号
I like Perl for this one: 我为此喜欢Perl:
The -i option will save the original file with a.bak extension. -i选项将保存带有a.bak扩展名的原始文件。
$ perl -i.bak -pe 's/^AB_/YZ_/' *.txt
grep -lr "AB_" ./ | while read file
do
echo "Change file $file ..."
sed -i 's/AB_/YZ_/g' ${file}
done
sed will take multiple files as arguments, so this should work: sed将多个文件作为参数,因此应该可以工作:
sed -i '/AB_/s//YZ_/g' *
(Note that -i
is non-standard) (请注意, -i
是非标准的)
sed one-liner answer sed单线答案
Find php files in the directory containing string "foo" and replace all occurences with "bar" 在包含字符串“ foo”的目录中查找php文件,并将所有出现的内容替换为“ bar”
grep -l foo *.php | grep -l foo * .php | xargs sed -i '' s/foo/bar/g xargs sed -i''s / foo / bar / g
To recurse through directories 遍历目录
grep -rl foo * | grep -rl foo * | xargs sed -i '' s/foo/bar/g xargs sed -i''s / foo / bar / g
(just done successfully on 8100 files) (仅在8100个文件上成功完成)
grep -rl bar * | grep -rl bar * | wc -l 8102 wc -l 8102
To replace every occurrence of a certain word / string in a ton of files spanning multiple directories, and this is the quickest way I've found to do it. 要替换跨越多个目录的大量文件中某个单词/字符串的每次出现,这是我找到的最快方法。 It uses grep to search for a certain word and if it find its it runs sed to replace the strings you want. 它使用grep搜索某个单词,如果找到它,则运行sed替换您想要的字符串。
grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.