CLI tip 3: place backups in another directory with GNU sed
You can use *
to place backups of original files in another directory when using the -i
option with GNU sed
. Consider these two sample input files in the current directory:
$ cat f1.txt
good morning
that was good, just too good!
$ cat f2.txt
goodie goodbye
Create a backups
directory and use *
under this directory as a placeholder for the filenames passed to the sed
command.
$ mkdir backups
$ sed -i'backups/*' 's/good/nice/' f1.txt f2.txt
$ ls backups/
f1.txt f2.txt
# modified content
$ cat f1.txt
nice morning
that was nice, just too good!
$ cat f2.txt
niceie goodbye
# backed-up original content
$ cat backups/f1.txt
good morning
that was good, just too good!
$ cat backups/f2.txt
goodie goodbye
Since *
expands to the name of the input files, you can also use this feature when you need to add a prefix for the backups.
$ sed -i'bkp.*' 's/green/yellow/' colors.txt
$ ls *colors*
bkp.colors.txt colors.txt
The *
trick works with Perl as well, see In-place file editing chapter from my Perl One-Liners Guide ebook for examples.
Video demo:
See my CLI text processing with GNU sed ebook if you are interested in learning about the GNU sed
command in more detail.