newzad
newzad

Reputation: 706

extract specific line from a file using awk

The data in the file:

...
... 
a b c d letters
f g h i letters
j k     letters
...
...

Using,

awk '/letters/' file

The result is:

a b c d letters
f g h i letters
j k     letters

However I want to have the following result (without tab and 'letters' word and single line would be better):

a b c d e f g h i j k

How can I achieve this?

Upvotes: 0

Views: 164

Answers (3)

Bruce Barnett
Bruce Barnett

Reputation: 948

Well, you can search for letters, delete the last field, and concatenate the rest of the line into a single variable A, then print that variable out at the end.

#!/usr/bin/awk -f
/letters/ {$NF="";A=A $0}
END{print A}

It doesn't remove any replications. But you didn't ask for that.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246807

I'd use

output=$(awk '$NF=="letters" {$NF="";print}' file)
echo $output   # without double quotes

Upvotes: 1

Kent
Kent

Reputation: 195059

quick and dirty:

awk '$NF=="letters"{sub($NF,"");s=s $0}END{sub(/ *$/,"",s);print s}' file

with your example:

kent$  echo "...
... 
a b c d letters
f g h i letters
j k     letters
...
..."|awk '$NF=="letters"{sub($NF,"");s=s $0}END{sub(/ *$/,"",s);print s}'                                                                                                   
a b c d f g h i j k

so output in oneline, without trailing spaces.

Upvotes: 1

Related Questions