unix find and replace characters with strings for multiple characters
12,022
You can use -e
switch in sed to input multiple commands like this:
sed -i.bak -e 's/a/apple/g' -e 's/b/bat/g' -e 's/c/cat/g'
Author by
noobcoder
Updated on June 04, 2022Comments
-
noobcoder almost 2 years
I want to replace all occurrences of certain characters in my file with words. My question is, can I do that for all the characters using a single command. I am using the following command for replacing every occurrence of 'a' with 'apples'
sed 's/a/apple/g' sample.txt
I don't want to write 3 or 4 similar commands to replace every occurrence of 'b', 'c', 'd' with some words. Is there any way out to extend the above command to suit my need or do I need to use the same three times ?
-
noobcoder almost 11 yearsThis sounds good. But does it actually modify the contents of the file or does this simply display it on the terminal ? Using the sed command for me simply displays the changes in the terminal but When I open the file, I see the old unmodified contents
-
anubhava almost 11 yearsI have added
-i.bak
flag to enable inline editing, this will save the changes in the file itself. -
noobcoder almost 11 yearsThis worked perfectly. However, does the .bak serve as a backup file? If so, when is it actually useful ? Can't I simply use sed -i -e 's/a/apple/g' and so on ?
-
anubhava almost 11 years
.bak
keeps the original content of your file which is for safety measures if anything goes wrong then you can get the original file. -
noobcoder almost 11 yearsI get it. Now I get the logic.
-
noobcoder almost 11 yearsI did that immediately but it asked me to wait for 5 minutes.