Home > database >  Keeping the last two fields in an input line in linux
Keeping the last two fields in an input line in linux

Time:01-05

I have the following problem:

I need to process lines structured as follows:

<e_1> <e_2> ... <e_n-1> <e_n>

where each <e_i> (except for <e_n>) is separated from the next by a single space character. The actual number of <e_i> elements in each line is always at least two, but otherwise unpredictable: one line might consist of five such elements, while the next might have twelve.

For each such line I must remove all the elements, except for the last two - e.g. if the input line is

a b c d e

after processing I should end up with the line

d e

What tool accessible from a bash script would allow me to pull this off?

CodePudding user response:

Just use awk to filter the last two columns:

awk '{print $(NF-1), $NF}'

eg:

$ printf 'a b c d e\nf g\na b c\n' | awk '{print $(NF-1), $NF}'
d e
f g
b c

CodePudding user response:

Actually, immediately after posting this I noticed that a combination of rev and cut will do the trick.

CodePudding user response:

A sed one-liner:

sed 's/.* \(.* .*\)$/\1/'
  •  Tags:  
  • Related