Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a string in multiple files using grep and sed when the -i argument is not supported?

Tags:

grep

unix

macos

sed

I have tried this command,

grep '/static' dir/* | xargs sed -i 's/\/static//g'

but the version of sed I am using does not support the -i argument.

To replace a string in a file, to the same input file as the output, I normally do this:

sed 's/\/static//g' filename.txt > new_filename.txt ; mv new_filename.txt filename.txt
like image 419
davierc Avatar asked Aug 13 '12 21:08

davierc


People also ask

How do you use sed command to replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do you do multiple sed replacements?

You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file). sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file , in-place.

Which is faster awk or sed?

Generally I would say grep is the fastest one, sed is the slowest. Of course this depends on what are you doing exactly. I find awk much faster than sed . You can speed up grep if you don't need real regular expressions but only simple fixed strings (option -F).

Which sed command is used for replacement?

Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.


2 Answers

OS X's version of sed does support -i, but it requires an argument to tell it what file extension to use for the backup file (or "" for no backup). BTW, you want grep -l to get just the filenames.

grep -l '/static' dir/* | xargs sed -i "" 's/\/static//g'
like image 107
Gordon Davisson Avatar answered Oct 18 '22 10:10

Gordon Davisson


Use perl:

$ perl -pi.bak -e 's@/static@@g' dir/*
like image 41
Diego Torres Milano Avatar answered Oct 18 '22 11:10

Diego Torres Milano