Coenster
Coenster

Reputation: 125

How to retrieve digits including the separator "."

I am using grep to get a string like this: ANS_LENGTH=266.50 then I use sed to only get the digits: 266.50

This is my full command: grep --text 'ANS_LENGTH=' log.txt | sed -e 's/[^[[:digit:]]]*//g'

The result is : 26650

How can this line be changed so the result still shows the separator: 266.50

Upvotes: 1

Views: 62

Answers (3)

Jotne
Jotne

Reputation: 41456

Here is some awk example:

cat file:
some data ANS_LENGTH=266.50 other=22
not mye data=43

gnu awk (due to RS)

awk '/ANS_LENGTH/ {f=NR} f&&NR-1==f' RS="[ =]" file
266.50

awk '/ANS_LENGTH/ {getline;print}' RS="[ =]" file
266.50

Plain awk

awk -F"[ =]" '{for(i=1;i<=NF;i++) if ($i=="ANS_LENGTH") print $(i+1)}' file
266.50

awk '{for(i=1;i<=NF;i++) if ($i~"ANS_LENGTH") {split($i,a,"=");print a[2]}}' file
266.50

Upvotes: 0

Ian Petts
Ian Petts

Reputation: 1350

You need to match a literal dot as well as the digits.

Try sed -e 's/[^[[:digit:]\.]]*//g'

The dot will match any single character. Escaping it with the backslash will match only a literal dot.

Upvotes: 1

jaypal singh
jaypal singh

Reputation: 77105

You don't need grep if you are going to use sed. Just use sed' // to match the lines you need to print.

sed -n '/ANS_LENGTH/s/[^=]*=\(.*\)/\1/p' log.txt
  • -n will suppress printing of lines that do not match /ANS_LENGTH/
  • Using captured group we print the value next to = sign.
  • p flag at the end allows to print the lines that matches our //.

If your grep happens to support -P option then you can do:

grep -oP '(?<=ANS_LENGTH=).*' log.txt
  • (?<=...) is a look-behind construct that allows us to match the lines you need. This requires the -P option
  • -o allows us to print only the value part.

Upvotes: 2

Related Questions