SED- Stream Editor
It is one of the most prominent text-processing utilities on GNU/Linux. It is stream oriented and uses simple programming language. It is capable of solving complex text processing tasks with few lines of code. This easy, yet powerful utility makes GNU/Linux more interesting.
I knew the power of SED but was unaware about how to use it correctly.
I recently faced a problem when I had to run a project on a server and had to change the credentials like password there. The problem was that I had about 15 or more files in which changes were to be made. I could change the username easily by issuing the following command:
find . -type f -exec sed -i 's/<oldname>/<newname>/g' {} +
But when it came to changing password, I went into trouble because the old password was “a” and when I tried using the following on backup of the same folder.
find . -type f -exec sed -i 's/'a'/'prit'/g' {} +
The problem was that ‘a’ occured so many times in so many files at numerous places and I only wanted to replace the “a” meant for password.
('localhost','pritika','a')
So, I pinged my friend Mandeep Singh and asked him if he could help me in the solution.
He suggested to use the following to get the file names in which ‘a’ was present in the password field:
grep -rl ",'a')"
and then said to try this one:
sed 's/'"'a'"'/'"'password'"'/g' somefile.php
This was working. But I had to use it for multiple files. I used for loop for that. As most of the file names were starting from t. So I chose to use it for all files starting from t.
for i in t*; do sed -i 's/'"'a'"'/'"'prit'"'/g' $i; done
And still the problem was not fully solved. There were some files where “a” was specified and not ‘a’ and the replacement didn’t take place there.
So, I used the sed command again for those left over files.
sed -i 's/'""a""'/'""prit""'/g' t_apply.php action.php t_index.php t_jobdetails.php
And finally the purpose was solved.
One important lesson that do test before replacing in the actual file or the replacements can affect the file badly or better you use -i.bak instead of i as it will create a backup file.
Thanks for you patience Mandeep and sorry for the delay I made in writing this blog.