-1

I have already followed this query @ (How to replace a string in multiple files in linux command line).

My question is rather an extension of the same.

I want to check only specific file extensions in the subfolders also but not every file extension.

What I have already tried:

grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @

My problem: It is changing in every other file format as well. I want to search and replace only in one file extension.

Please add another answer where I can change the entire line of a file as well not just one word.

Thanks in advance.

2 Answers2

0
  1. Simplest solution is to use complex grep command:

    grep -rli --include="*.html" --include=".json" 'old-word' *

The disadvantage of this solution. Is that you do not have clear control which files are scanned.

  1. Better suggesting to tune a find command to locate your desired files.

Using RegExp filtering option -regex to filter file names.

So you verify the correct files are scanned.

Than feed the find command result to grep scanning list.

Example:

Assuming you are looking for file extensions txt pdf html .

Assuming your search path begins in /home/user/data

 find /home/user/data -regex ".*\.\(html\|txt\|pdf\)$"

Once you have located your files. It is possible to grep match each file from the the above find command:

 grep -rli 'old-word' $( find /home/user/data -regex ".*\.\(html\|txt\|pdf\)$" ) 
Dudi Boy
  • 4,551
  • 1
  • 15
  • 30
0

I hope someone will take advantage of this coding line even if the answer or solution is too,late. this is the command line that always works for me.

find ./ -type f | xargs sed -i 's/old-word/new-word/g'

Enjoy. :)

Fedor
  • 17,146
  • 13
  • 40
  • 131