Thursday, August 25, 2011

Replacing a string recurcively in all files of a folder in Linux

Today I have come to a situation in which I have to search for a particular string in a Directory/Directories recurcively and if found, then have to replace with other string.
                  So here is simple one line command using for loop or you can also make a good script using the below command.

Go to directory where you have to search the particular and fire below command.

# for file in $(grep -rli *string to search* *);           
   do  
          sed -i 's/*string to search*/*String to be replaced*/g' $file; 
  done

Note : * at end of grep is compulsory, but don't put with string you want to search. eg if you want search linux then write linux not *linux*. The * at end of grep command is astrerisk for searching all files.

Where,
Option with grep do following tasks..
-r : For recurcively search
-i : For all matches(whether small or capital)
-l : Stop after fisrt occurence

Option with sed do following tasks..
-i : edit the orginal file permanently
Note : if -e option with sed shows you result on screen and do not change the contents of file permanetly.

No comments:

Post a Comment

Integrate Jenkins with Azure Key Vault

Jenkins has been one of the most used CI/CD tools. For every tool which we are using in our daily life, it becomes really challenges when ...