Frage

I want to let awk print all the numbers from the input, so I wrote

echo 2 1a 12121 -1212 abc | 
awk ' { for (i=1;i<=NF;i++) if ($i ~ /[-.0-9]*/) print $i; } '

What I want to say is 'strings consists of '0-9' '.' '-', but in the output it prints every fields out, what did I do wrong?

War es hilfreich?

Lösung

/[-.0-9]*/

This means zero or more number, . or -
Since abc does contain zero of characters above it will be printed.

Change to + meaning one or more:

PS this will also print field with a single . and a single -

echo "2 1a 12121 -1212 abc .  more -  hey 45.62" |  awk '{for (i=1;i<=NF;i++) if ($i~/[0-9.-]+/) print $i}'
2
1a
12121
-1212
.
-
45.62

So I would use some like this to print number only:

echo "2 1a 12121 -1212 abc .  more -  hey 45.62" |  awk '{for (i=1;i<=NF;i++) if ($i~/^-?[0-9]+\.?[0-9]*$/) print $i}'
2
12121
-1212
45.62

^ Start of field
-?contain one - or none
/[0-9]+\.?[0-9]*/
[0-9]+ one or more digit
\.? 0 or 1 .
[0-9]* zero or more digits
$ end of filed

Andere Tipps

Do you want like this?

echo 2 1a 12121 -1212 abc | awk '{ for (i=1;i<=NF;i++) if ($i ~ /-?[0-9]+\.?[0-9]*$/) print $i; }'
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top