Home > database >  Sed and grep in multiple files
Sed and grep in multiple files

Time:10-05

I want to use "sed" and "grep" to search and replace in multiples files, excluding some directories. I run this command:

$ grep -RnI --exclude-dir={node_modules,install,build} 'chaine1' /projets/ | sed -i 's/chaine1/chaine2/'

I get this message:

sed: pas de fichier d'entrée

I also tried with these two commands:

$ grep -RnI --exclude-dir={node_modules,install,build} 'chaine1' . | xargs -0 sed -i 's/chaine2/chaine2/'
$ grep -RnI --exclude-dir={node_modules,install,build} 'chaine2' . -exec sed -i 's/chaine1/chaine2/g' {} \;

But,it doesn't work!!

Could you help me please?

Thanks in advance.

CodePudding user response:

You want find with -exec. Don't bother running grep, sed will only change lines containing your pattern anyway.

find \( -name node_modules -o -name install -o -name build \) -prune \
  -o -type f -exec sed -i 's/chaine1/chaine2/' {}  

CodePudding user response:

First, the direct outputs of grep command are not file paths. They look like this {file_path}:{line_no}:{content}. So the first thing you need to do is to extract file paths. We can do this use cut command or use -l option of grep.

# This will print {file_path}
$ echo {file_path}:{line_no}:{content} | cut -f 1 -d ":"

# This is a better solution, because it only prints each file once even though
# the grep pattern appears at many lines of a file.
$ grep -RlI --exclude-dir={node_modules,install,build} "chaine1" /projets/

Second, sed -i does not read from stdin. We can use xargs to read each file path from stdin and then pass it to sed as its argument. You have already done this.

The complete command like this:

$ grep -RlI --exclude-dir={node_modules,install,build} "chaine1" /projets/ | xargs -i sed -i 's/chaine1/chaine2/' {}
  • Related