Skip to content
Advertisement

Sed: select first part of price

Seems that my sed command is not working. I am trying to select the 2 in $2.99. However, no matter how I seem to type the regex, it will only give the .99
I want to select everything (every number) that is not the dollar sign up to the period.
Any suggestions?

echo "$2.99" | sed -e 's:^([^\$]*).:the price is 1.:'

Advertisement

Answer

The problem is not with your sed but with echo. Note that $2 when expanded under double quotes is the positional parameter two which expands nothing in this case. So in essence you’re doing

echo ".99" | something

The right approach would be

echo '$2.99' | sed -E 's/$([[:digit:]]*)..*$/The price is Dollar 1/'
#Note that $2 inside single quotes is literal $2

Output

The price is Dollar 2

Note : The 1 in the substitution part expands to the matched part inside the parenthesis.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement