Patrick
Patrick

Reputation: 13

Filtering a variable in bash script using regex tr or awk

row1=$('+00 00:30:07.880000')

rowX=$('row1 | tr -dc '0-9')

I basically want to filter out all the special characters and space.

I wish to have a output as follows.

echo $'row1' = 003007.880000

Upvotes: 1

Views: 1582

Answers (2)

pjh
pjh

Reputation: 8174

You don't need regular expressions or external commands like tr for this. Bash's built-in parameter expansion can do it:

row1='+00 00:30:07.880000'
row1=${row1//[^0-9.]/}
echo "row1=$row1"

outputs row1=00003007.880000.

The output has two leading zeros that are not in the output suggested in the question. Maybe there's an unstated requirement to remove prefixes delimited by spaces. If that is the case, possible code is:

row1='+00 00:30:07.880000'
row1=${row1##* }
row1=${row1//[^0-9.]/}
echo "row1=$row1"

That outputs row1=003007.880000.

See How do I do string manipulations in bash? for explanations of ${row1//[^0-9.]/} and ${row1##* }.

Upvotes: 2

Matias Barrios
Matias Barrios

Reputation: 5056

This is the easiest way to do that :

$ echo '+00 00:30:07.880000' | tr -dc '[0-9].'
00003007880000

Regards!

Upvotes: 1

Related Questions