简体   繁体   中英

Replace dollar sign with 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?

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

If you only want to remove the character '$' from the string, there is an alternative way using Shell Parameter Expansion. For example:

v1='abc $def ghi'
v2='abc $123def ghi'
echo ${v1/$/}
echo ${v2/$/}

The syntax is: ${parameter/pattern/string}

If you want to know more about Shell Parameters Expansion look at: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion

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 "$"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM