tsunpo
tsunpo

Reputation: 31

How can I extract a subset from a column/field using awk?

I wondered how can I extract a subset from a column/field using awk?

Here is the input file test.txt:

aaa bbb ccc=0.7707;ddd=0.21

I would like to be able to extract figure "0.21" from the 3rd column, and output it with the 1st and 2nd columns:

aaa bbb 0.21

I have tried and used the code below but failed:

awk 'BEGIN { OFS = "\t" } { $4 = /^ddd=(+\d)/ ; print $1,$2,$4 }' test.txt

Please help!

Many thanks, TP

Upvotes: 2

Views: 2047

Answers (3)

Jotne
Jotne

Reputation: 41446

Another awk

awk '{split($3,a,"=");print $1,$2,a[3]}'
aaa bbb 0.21

Upvotes: 0

devnull
devnull

Reputation: 123458

You could use gsub:

awk 'BEGIN { OFS = "\t" } { gsub(/.*=/, "", $3); print $1,$2,$3 }' text.txt

For your input, it'd give:

aaa bbb 0.21

Upvotes: 0

Steve
Steve

Reputation: 54392

You can specify multiple delimiters using the -F flag or setting FS in the BEGIN block. For example:

echo "aaa bbb ccc=0.7707;ddd=0.21" | awk -F "[ =]" '{ print $1, $2, $NF }'

Results:

aaa bbb 0.21

Upvotes: 1

Related Questions