Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace dollar sign with sed

Tags:

linux

bash

sed

I try to replace all dollar signs in a string using sed. However, not only the dollar sign gets replaced but the whole string that follows.

$ echo "abc $def ghi" | sed 's/$//g'
$ abc ghi

If at least one number is following the dollar sign only the part before the first non-number gets replaced:

$ echo "abc $123def ghi" | sed 's/$//g'
$ abc def ghi

What is going on?

like image 322
Severin Avatar asked Aug 08 '17 08:08

Severin


2 Answers

echo 'abc $def ghi' | sed 's/\$//g'

In echo use single quote, if not it means that there is variable def and its substitution and if you don't have variable def it's empty. In sed, you need to escape the dollar sign, because otherwise it means "anchor to the end of the line."

like image 56
tso Avatar answered Sep 21 '22 13:09

tso


tr should be used for this task, not sed.

Use it with single quotes in echo to prevent parameter expansion.

echo 'abc $123def ghi' | tr -d "$"

like image 30
Andre Figueiredo Avatar answered Sep 22 '22 13:09

Andre Figueiredo