[ACCEPTED]-What GNU/Linux command-line tool would I use for performing a search and replace on a file?-gnu
sed 's/a.*b/xyz/g;' old_file > new_file
GNU sed (which you probably have) is even more 7 versatile:
sed -r --in-place 's/a(.*)b/x\1y/g;' your_file
Here is a brief explanation of 6 those options:
-i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes 5 backup if extension supplied)
-r, --regexp-extended use extended 4 regular expressions in the script.
The FreeBSD, NetBSD and 3 OpenBSD versions also supports these options.
If 2 you want to learn more about sed, Cori has suggested 1 this tutorial.
Perl was invented for this:
perl -pi -e 's/foo/bar/g;' *.txt
Any normal s/// pattern 3 in those single quotes. You can keep a backup 2 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 1 that's really more sed's job.
Consider Ruby as an alternative to Perl. It 11 stole most of Perl's one-liner commandline 10 args (-i
, -p
, -l
, -e
, -n
) and auto-sets $_
for you like 9 Perl does and has plenty of regex goodness. Additionally 8 Ruby's syntax may be more comfortable and 7 easier to read or write than Perl's or sed's. (Or 6 not, depending on your tastes.)
ruby -pi.bak -e '$_.gsub!(/foo|bar/){|x| x.upcase}' *.txt
vs.
perl -pi.bak -e 's/(foo|bar)/\U\1/g' *.txt
In many 5 cases when dealing with one-liners, performance 4 isn't enough of an issue to care whether 3 you use lightweight sed or heavyweight Perl 2 or heaveier-weight Ruby. Use whatever is 1 easiest to write.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.