Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sed to replace multiple chars in a string?

Tags:

linux

sed

I want to replace some chars of a string with sed.

I tried the following two approaches, but I need to know if there is a more elegant form to get the same result, without using the pipes or the -e option:

sed 's#a#A#g' test.txt | sed 's#l#23#g' > test2.txt
sed -e 's#a#A#g' -e 's#l#23#g' test.txt > test2.txt
like image 652
neo33 Avatar asked Feb 24 '16 21:02

neo33


People also ask

How to replace everything after the match in sed command?

The following ` sed ` command shows the use of ‘ c ‘ to replace everything after the match. Here, ‘ c ‘ indicates the change. The command will search the word ‘ present ‘ in the file and replace everything of the line with the text, ‘ This line is replaced ‘ if the word exists in any line of the file.

How to use sed command to delete a specific character?

This sed command finds the pattern and replaces with another pattern. When the replace is left empty, the pattern/element found gets deleted. 1. To remove a specific character, say 'a' This will remove the first occurence of 'a' in every line of the file.

How to replace multiple lines based on search pattern in SED?

Create a sed file named to replace.sed with the following content to replace the multiple lines based on the search pattern. Here, the word ‘ CSE ‘ will be searched in the text file, and if the match exists, then it will again search the number 35 and 15. If the second match exists in the file, then it will be replaced by the number 45.

What are the different types of Substitution commands in SED?

s - The substitute command, probably the most used command in sed. / / / - Delimiter character. It can be any character but usually the slash ( /) character is used. SEARCH_REGEX - Normal string or a regular expression to search for. REPLACEMENT - The replacement string. g - Global replacement flag.


1 Answers

Instead of multiple -e options, you can separate commands with ; in a single argument.

sed 's/a/A/g; s/1/23/g' test.txt > test2.txt

If you're looking for a way to do multiple substitutions in a single command, I don't think there's a way. If they were all single-character replacements you could use a command like y/abc/123, which would replace a with 1, b with 2, and c with 3. But there's no multi-character version of this.

like image 118
Barmar Avatar answered Nov 16 '22 02:11

Barmar