Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Replace Inside a Text File from a Bash Command

What's the simplest way to do a find and replace for a given input string, say abc, and replace with another string, say XYZ in file /tmp/file.txt?

I am writting an app and using IronPython to execute commands through SSH — but I don't know Unix that well and don't know what to look for.

I have heard that Bash, apart from being a command line interface, can be a very powerful scripting language. So, if this is true, I assume you can perform actions like these.

Can I do it with bash, and what's the simplest (one line) script to achieve my goal?

like image 812
Ash Avatar asked Feb 08 '09 11:02

Ash


People also ask

How do I replace a substring in bash?

To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation. We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.

Where is find and replace in text editor Linux?

Open the Replace tool by clicking Menu button ▸ Find and Replace… or press Ctrl + H . Enter the text that you wish to replace into the Find field. Enter the new, replacement text into the Replace with field. Once you have entered the original and replacement text, you can add extra parameters to the search.


1 Answers

The easiest way is to use sed (or perl):

sed -i -e 's/abc/XYZ/g' /tmp/file.txt 

Which will invoke sed to do an in-place edit due to the -i option. This can be called from bash.

If you really really want to use just bash, then the following can work:

while IFS='' read -r a; do     echo "${a//abc/XYZ}" done < /tmp/file.txt > /tmp/file.txt.t mv /tmp/file.txt{.t,} 

This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The move at the end just moves temporary to the original name. (For robustness and security, the temporary file name should not be static or predictable, but let's not go there.)

For Mac users:

sed -i '' 's/abc/XYZ/g' /tmp/file.txt (See the comment below why)

like image 177
johnny Avatar answered Oct 12 '22 10:10

johnny