What GNU/Linux command-line tool would I use for performing a search and replace on a file?
Can the search text, and replacement, be specified in a regex format?
SED command in UNIX stands for stream editor and it can perform lots of functions on file like searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace.
The find command is used to search and locate the list of files and directories based on conditions you specify for files that match the arguments. find command can be used in a variety of conditions like you can find files by permissions, users, groups, file types, date, size, and other possible criteria.
replace looks for all occurrences of string from and replaces it with string to. You can specify one or more pairs of strings to search/replace in a single replace command. Use the -- option to indicate where the string-replacement list ends and the file names begin.
sed 's/a.*b/xyz/g;' old_file > new_file
GNU sed (which you probably have) is even more versatile:
sed -r --in-place 's/a(.*)b/x\1y/g;' your_file
Here is a brief explanation of those options:
-i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied)
-r, --regexp-extended use extended regular expressions in the script.
The FreeBSD, NetBSD and OpenBSD versions also supports these options.
If you want to learn more about sed, Cori has suggested this tutorial.
Perl was invented for this:
perl -pi -e 's/foo/bar/g;' *.txt
Any normal s/// pattern in those single quotes. You can keep a backup with something like this:
perl -pi.bak -e 's/foo/bar/g;' *.txt
Or pipeline:
cat file.txt | perl -ne 's/foo/bar/g;' | less
But that's really more sed's job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With