for example:

Let say this is a file num

1.   hi
2.   hello
3.   hey

How do I remove the white spaces to just get the hello?

$ head -1 num | (what should be here to make it below)

2 Answers 2


awk uses code built like patterns with actions. The "pattern" that you have here is that you'd like to do something with the first line only, and the "action" is "print the second column (and then quit)":

awk 'NR == 1 { print $2; exit }' file

The exit is an optional optimization in this case and could be removed (there is no other line for which NR would be 1). NR means "the ordinal number of the current line" or "the number of lines read so far".

In this simple case, building from your head attempt:

head -n 1 file | while read -r num word; do printf '%s\n' "$word"; done


read -r num word <file
printf '%s\n' "$word"

would accomplish the same thing as we're only interested in the first line.

... but parsing text in the shell itself is error-prone and should be avoided. With a small example like this, it would work ok though.

You used the word slice in the title, which in English has the same meaning as cut, which is another Unix utility. It could be used here, but it's a bit simplistic and how you use it depends on the delimiter character(s) between the two columns of data.

  1. If you have a single tab between the columns:

    head -n 1 file | cut -f 2
  2. If you have three spaces between the columns:

    head -n 1 file | cut -d ' ' -f 4

It depends whether you want the first line or a specific line (foo is your file).

If you just want to split a specific line, use

$ awk 'NR==1 { print $2; exit}' foo
$ awk 'NR==2 { print $2; exit}' foo

If you want to select the line based on content, use

$ awk '/1./ { print $2; exit }' foo
$ awk '/2./ { print $2; exit }' foo
$ awk '$1 ~ 2. { print $2; exit }' foo
$ awk '/hello/ { print $2; exit }' foo

In all cases, the exit ensures that only the first match gets printed (and it also prevents the processing of the whole file).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.