Contents of most text files change during the life of the file , and it is common to find yourself trying to search and replace certain text across multiple files. In Linux, this is a fairly easy task. Let us go through some of the commands you will need to perform this task and then finally construct a single liner to do the job.
- grep is your best friend when it comes to finding a string in a file. In this case we are looking for the string “REPLACEME” in current directory and across multiple files –
$ grep -r REPLACEME *
host.conf:# The "REPLACEME" line is only used by old versions of the C library.
host.conf:order hosts,REPLACEME,bind
hostname:REPLACEME
hosts.deny:ALL: REPLACEME
If we are interested only in the files which contains this particular text –
$ grep -lr REPLACEME *
host.conf
hostname
hosts.deny
- sed is a tool of choice for inline editing of files –
$ cat data
This text will be replaced - REPLACEME
$ sed -i 's/REPLACEME/NEWTEXT/g' data
$ cat data
This text will be replaced - NEWTEXT
From here, there are multiple ways to skin the cat – we can loop through the files and do the replacement or we can let the commands do the replacement with a wildcard.
For loop style update -
$ for f in $(grep -lr REPLACEME *); do echo "*** File: ${f} ***" ; sed -i 's/REPLACEME/NEWTEXT/g' $f; done
*** File: host.conf ***
*** File: hostname ***
*** File: hosts.deny ***
$ grep -lr REPLACEME *
$ grep -lr NEWTEXT *
data
host.conf
hostname
hosts.deny
Actually the above for loop is redundant, sed can make changes across multiple files –
sed -i 's/REPLACEME/NEWTEXT/g' *