[英]Find and Replace with grep and sed in OSX
I am trying to replace the string #archive
in a bunch of files in the same directory with ~archive
. 我试图替换字符串
#archive
在使用相同的目录一堆文件~archive
。 My filenames have spaces in them and are rather long. 我的文件名中有空格,而且很长。 I checked and someone said that I have to invoke grep with -Z and xargs with -0.
我检查了一下,有人说我必须用-Z调用grep,用-0调用xargs。 And so I did.
所以我做到了。
The current terminal command I have is this: 我当前的终端命令是这样的:
grep -lZ '#archive' ~/dropbox/documents/notes/Archive/* | xargs -0 sed -i "" 's|#archive|~archive|g'
And the output I get is this: 我得到的输出是这样的:
sed: /Users/bobthebuilder/dropbox/documents/notes/Archive/20130824_1553_I_Kino Interesting Books.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/20131003_1011_R_ExpensesOct13.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/20131111_1205_RI_SocialConnect.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/20131111_2233_I_GymNov13Dec13.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/20131112_1121_I_LifeChallenge.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/20131112_1242__PaperlessLiving.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/20131112_1243__Polymath.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/20131112_1327__ORDPlanning.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/20131124_1126__YunheProjectExcel.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/Contact Information.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/Excruciatingly Useful Shortcuts.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/How does this thing work?.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/Mail Migration.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/Markdownify.txt
/Users/bobthebuilder/dropbox/documents/notes/Archive/This is the title of a note.txt
: File name too long
And nothing is replaced. 并没有什么被取代。
I also tried: 我也尝试过:
| => grep -l --null '#archive' ~/dropbox/documents/notes/Archive/* | xargs -0 sed -i "" 's|#archive|~archive|g'
sed: RE error: illegal byte sequence
Help would be appreciated! 帮助将不胜感激!
如果文件在同一文件夹中
sed -i "" 's/#archive/~archive/' ~/dropbox/documents/notes/Archive/*
If you're going to use the -i
arg for sed
, you will need to put the command string after a -e
. 如果要将
-i
arg用于sed
,则需要将命令字符串放在-e
。
grep -l --null '#archive' ~/dropbox/documents/notes/Archive/* | xargs -0 sed -e 's|#archive|~archive|g' -i ""
However, @NeronLeVelo's answer is also correct, and simpler if you don't need recursion (which you aren't using). 但是,@ NeronLeVelo的答案也是正确的,并且如果不需要递归(不使用递归),则更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.