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?
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.
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.
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.)
sed -i '' 's/abc/XYZ/g' /tmp/file.txt
(See the comment below why)
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