4

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 ?

3
  • Be careful when you get to replacing the e characters as it will affect the e in apple as well. You may want to investigate the Regexp features of sed, especially the "word boundary" characters. Commented May 22, 2013 at 4:34
  • @Intermernet What do you suggest I do in that case? I also noticed that using the command I mentioned, I get a replaced output in my terminal but the file contents are not modified. Commented May 22, 2013 at 4:37
  • Check out sed -i. It should allow in-place modification but is sometimes dangerous! copy the file first! Commented May 22, 2013 at 4:40

1 Answer 1

3

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'
Sign up to request clarification or add additional context in comments.

6 Comments

This 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
I have added -i.bak flag to enable inline editing, this will save the changes in the file itself.
This 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 ?
.bak keeps the original content of your file which is for safety measures if anything goes wrong then you can get the original file.
I get it. Now I get the logic.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.