pm1359
pm1359

Reputation: 632

Regular expression with awk return only column with one numeric character?

I have two different type of log lines and the field $5 is:

ffe5a6fb-2933-4c01-855d-3033933600bf
3

How can write a regular expression with awk in order to extract only fields with one character?

This is my solution however it is not working and it will return everything!

awk '/[0-9]\+/ {print $5}'

I will be appreciated for any help?

Upvotes: 0

Views: 599

Answers (3)

heemayl
heemayl

Reputation: 42007

Do:

awk '$5~/^.$/ {print $5}' file.txt

To match only a digit:

awk '$5~/^[0-9]$/ {print $5}' file.txt

Example:

$ cat file.txt
abcdX1yad45das ffe5a6fb-2933-4c01-855d-3033933600bf ffe5a6fb-2933-4c01-855d-3033933600bf ffe5a6fb-2933-4c01-855d-3033933600bf ffe5a6fb-2933-4c01-855d-3033933600bf 3 foo
abcdX1yad45das ffe5a6fb-2933-4c01-855d-3033933600bf ffe5a6fb-2933-4c01-855d-3033933600bf ffe5a6fb-2933-4c01-855d-3033933600bf 3 foo
abcdX2fad45das
abcdX3had45das
abcdX4wad45das
abcdX5mad45das

$ awk '$5~/^.$/ {print $5}' file.txt
3

Upvotes: 2

Tom Fenech
Tom Fenech

Reputation: 74615

It's marginally longer to write but if you only care about the length of the field, I think it's clearer to use length:

awk 'length($5) == 1 { print $5 }' file

Otherwise, if you want to match a single character in the range 0 to 9, that would be:

awk '$5 ~ /^[0-9]$/ { print $5 }' file

...or to match anything considered to be a digit in your locale:

awk '$5 ~ /^[[:digit:]]$/ { print $5 }' file

Some versions of awk (e.g. GNU awk) understand the shorthand \d instead of [[:digit:]].

Upvotes: 1

jgshawkey
jgshawkey

Reputation: 2122

Don't escape the "+" sign.

awk '/[0-9]+/ {print $5}'

Upvotes: 0

Related Questions