Skip to content
Advertisement

Find and replace a word in all the files, which is falling under a searching criteria at Unix

I want to replace a word in all the files inside all the sub directories, which satisfy some criteria.

Below is the elaborated situation.

I have to replace all the Word having case insensitive word like {classy, CLASSY, cLassy ,..} to word “Vintage”. Also I only need to replace it where it have a case insensitive word “insert” or “INSERT”.

So if i have 2 files having below content.

File1.txt
asd asdsd INSERT asdasd classy
asddsdff sdf sdff sdf  CLASSY
sfre asfert asdd asd insert asdgweg 
qwe asfer wrererw  werer wewer INSERT CLassy


File2.txt
fhfgh asdsd insert asdasd ClASSY
asddsdff dfg  sdff sdf  CLASSY
sdgg asfert dfg asd insert asdgweg CLASSY
qwe asfer wrererw  werer wewer INSERT 

I want to change the content of both the file as

File1.txt
asd asdsd INSERT asdasd Vintage
asddsdff sdf sdff sdf  CLASSY
sfre asfert asdd asd insert asdgweg 
qwe asfer wrererw  werer wewer INSERT Vintage

File2.txt
fhfgh asdsd insert asdasd Vintage
asddsdff dfg  sdff sdf  CLASSY
sdgg asfert dfg asd insert asdgweg Vintage
qwe asfer wrererw  werer wewer INSERT 

Below is the command I used , but it is not working fine. Can you please help me understand the issue.

find /rootFolderPath -name "*.txt" | xargs grep -i insert -exec sed -i -e 'classy/Vintage/I' -- {} +

Advertisement

Answer

You can use gnu-sed with find as:

cd /rootFolderPath
find . -name '*.txt' -exec 
     sed -i '/binsertb/I{s/bclassyb/Vintage/gI;}' {} +

Here is what sed command does:

  • -i: Inline editing
  • /binsertb/I: Search string insert in a line (case insensitive for I and b for word boundaries)
  • {s/bclassyb/Vintage/gI;}: If insert is found in a line then substitute classy with Vintage (again bis for word boundaries,Iis for case insensitive andg` is for global search)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement