Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep and sed with spaces in filenames

Currently, I have

grep -irl $schema $WORKDIR/ | xargs sed -i 's/'"$schema"'/EXI1/gI'

which doesn't work for filenames with spaces.

Any ideas, how to search and replace recursively for all files?

Thanks

like image 388
rojanu Avatar asked Jun 25 '13 11:06

rojanu


People also ask

What does SED and grep do in Linux?

This collection of sed and grep use cases might help you better understand how these commands can be used in Linux. Tools like sed (stream editor) and grep (global regular expression print) are powerful ways to save time and make your work faster.

How do I read a file name with spaces in it?

Your terminal may show the file name with space escaped with backslash if you press tab key for the filename. Read a file with spaces in filename To use a filename with spaces in it, you can wrap it in quotes like this: cat "file name with spaces"

Can I use spaces in file names in Linux terminal?

The one thing you'll notice that files in Linux usually do not contain names. Your teacher or colleague use underscore instead of spaces in file and directory names. It's not that you cannot use spaces in file names in Linux terminal. It's just that it creates additional pain and that's why you should avoid it wherever possible.

What does the G MEAN in sed command?

The g stands for global replace (meaning throughout the file). You can even change the servers’ regions in the file: This use case is more advanced. We’ll only remove comments ( #) from a file using sed:


2 Answers

Add the -Z (aka --null) flag to grep, and the -0 (also aka --null) flag to xargs. This will output NUL terminated file names, and tell xargs to read NUL terminated arguments.

eg.

grep -irlZ $schema $WORKDIR/ | xargs -0 sed -i 's/'"$schema"'/EXI1/gI'
like image 115
Hasturkun Avatar answered Oct 28 '22 01:10

Hasturkun


find with sed should work:

find $WORKDIR/ -type f -exec sed -i.bak "s/$schema/EXI1/gI" '{}' +

OR

find $WORKDIR/ -type f -print0 | xargs -0 sed -i.bak "s/$schema/EXI1/gI"
like image 22
anubhava Avatar answered Oct 28 '22 02:10

anubhava