Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What GNU/Linux command-line tool would I use for performing a search and replace on a file?

Tags:

regex

linux

sed

gnu

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?

like image 943
Ben Lever Avatar asked Oct 01 '08 02:10

Ben Lever


People also ask

What command can be used to perform a search and replace on a file or text stream?

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.

Which command is used to search files in Linux?

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.

What is replace command in Linux?

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.


2 Answers

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.

like image 71
Cristian Ciupitu Avatar answered Oct 06 '22 05:10

Cristian Ciupitu


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.

like image 41
Michael Cramer Avatar answered Oct 06 '22 04:10

Michael Cramer