Bash: A Better Way to Sed
So I frequently find myself in a situation where I need to modify files on a fairly programmatic basis, so sed has become a friend of mine for a lot of these situations. So lets start with some basic sed…
If I have a file..
# cat /etc/file.txt blah blah teststring blah blah
And I want to replace “teststring” with “productionvalue” then I could use sed.
# sed -i 's/teststring/productionvalue/g' /etc/file.txt
# cat /etc/file.txt blah blah productionvalue blah blah
This is all well and good, but recently I found a better way…
Using perl, not only can we make the change, but we also create a backup file of the original configuration.
# perl -pi.orig -e 's/teststring/productionvalue/g' /etc/file.txt
So now lets take a look at our original file with the .orig extension…
# cat /etc/file.txt.orig blah blah teststring blah blah
And finally our changed file…
# cat /etc/file.txt blah blah productionvalue blah blah
This is certainly a more useful way of making programmatic changes while retaining the ability to quickly recover from programmatic errors…
