Skip to content
Advertisement

How can I show only some words in a line using sed?

I’m trying to use sed to show only the 1st, 2nd, and 8th word in a line.

The problem I have is that the words are random, and the amount of spaces between the words are also random… For example:

QST334   FFR67     HHYT  87UYU HYHL 9876S   NJI QD112    989OPI

Is there a way to get this to output as just the 1st, 2nd, and 8th words:

QST334 FFR67 QD112

Thanks for any advice or hints for the right direction!

Advertisement

Answer

Use awk

awk '{print $1,$2,$8}' file

In action:

$ echo "QST334 FFR67 HHYT 87UYU HYHL 9876S NJI QD112 989OPI" | awk '{print $1,$2,$8}'
QST334 FFR67 QD112
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement