Input:
United+States
Output:
United States
I tried many times using sed
without success.
Input:
United+States
Output:
United States
I tried many times using sed
without success.
By default, sed
uses basic regular expressions (BRE), where the plus sign is not special. So you can use it in the s
command as you would use a regular character:
<<< 'United+States' sed 's/+/ /g'
If you want to modify a file with several instances in the same line (g
) or with several lines
sed 's/+/ /g' filename
If you use extended regular expressions (ERE, sed -E
in versions of sed
that support it), then you need to escape the plus:
sed -E 's/\+/ /g' ...
(See this question for the difference between the regex variants.)
man xterm
. You can find other special meanings too. Don't forget the addtion operator. Dot: In this answer ... simply means some characters, but generally, dot can mean several things depending on the context. Inside a sed s expression dot means 'any [single] character'.
– sudodus
Apr 13 '22 at 16:06
$ echo 'United+States' | tr '+' ' '
United States
Since you're only changing single characters, it's quicker to do it with tr
.
The equivalent sed
script would look either like
$ echo 'United+States' | sed 'y/+/ /'
United States
or
$ echo 'United+States' | sed 's/+/ /g'
United States
The y
command in sed
replaces all occurrences of the first set of characters (only +
here) with the corresponding character in the second set (only space here).
The s
command replaces the text that matches a regular expression with some text. With g
, it does it for every occurrence. Without it, only for the first one on each input line.
To change pluses to spaces only when they are flanked by words:
sed 's/\>+\</ /g'
This would change a+b
to a b
but would leave a + b
and a++b
unmodified.
The pattern \>
matches the zero width space at the end of a word, and \<
is analogous for the start of a word. GNU sed
also understands \b
(either start or end of a word), and BSD sed
knows about [[:<:]]
and [[:>:]]
which works just like \<
and \>
respectively.
You can check this example and work according to achieve your result.
Example:- This code makes the change and writes the modified file to "songs2.txt". The output file contains:
1, Justin Timberlake, Title 545, Price $7.30
2, Taylor Swift, Title 723, Price $7.90
3, Mick Jagger, Title 610, Price $7.90
4, Lady Gaga, Title 118, Price $7.30
5, Johnny Cash, Title 482, Price $6.50
6, Elvis Presley, Title 335, Price $7.30
7, John Lennon, Title 271, Price $7.90
If you want to replace all occurrences of "Cash" with "Trash" you use:
sed 's/Cash/Trash/' songs.txt > songs2.txt
Reference Link:- A Quick Guide to Using Sed Commands in Linux