Arpan
Arpan

Reputation: 993

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' -- {} +

Upvotes: 2

Views: 48

Answers (1)

anubhava
anubhava

Reputation: 786349

You can use gnu-sed with find as:

cd /rootFolderPath
find . -name '*.txt' -exec \
     sed -i '/\binsert\b/I{s/\bclassy\b/Vintage/gI;}' {} +

Here is what sed command does:

  • -i: Inline editing
  • /\binsert\b/I: Search string insert in a line (case insensitive for I and \b for word boundaries)
  • {s/\bclassy\b/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)

Upvotes: 5

Related Questions