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
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.
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.
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.
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.
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.
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