Really sorry if this has been asked before as it feels basic, I'm just not connecting the dots and it's making me tear my hair out!

Essentially I have a text file , and I'm assigning the second field of particular rows to a variable i.e

VAR=$(awk 'NR==1 {print $2}' entry.txt)

However, sometimes on row one in the text file, it will have 4 fields. I would like to say

   If ROW 1 has 4 fields  
        VAR = $2, $3 & $4 concatenated
        VAR = $2 

I'm sure this is basic awk, I'm just undertaking a small project and have never used it before. I know i should read a book, but this really is a tiny script!


awk 'NF == 4 { print $2 $3 $4; exit } { print $2; exit }' file

This concatenates the second, third and fourth fields if there are exactly four whitespace-delimited fields on the first line of the file. Otherwise, it will return the second field from the first line of the file. The program exits as soon as it has outputted anything, so we are certain that it's only the first line that we'll ever see.

With different logic:

awk 'NF == 4 { out = $2 $3 $4 } NF != 4 { out = $2 } { print out; exit }' file


awk '{ out = $2 } NF == 4 { out = out $3 $4 } { print out; exit }' file

Either of these commands goes inside your command substitution:

var=$( awk ... )
  • Thank you, even simply seeing these examples helped me understand my small syntax errors that ultimately lead to the hair-pulling! – Harry S Apr 23 '18 at 15:31
awk 'NR==1 && NF==4 { var=$2 $3 $4 } NR==1 && NF!=4 { var=$2 }' /path/to/input
  • Thank you, that was very helpful in understanding how to apply the problem to any row of a file – Harry S Apr 23 '18 at 15:32

You can do

awk '{$1=""; print (NF==4)?$0:$2; exit}' OFS= infile

The Ternary condition operator (NF==4)?$0:$2 checks if the Number of Fields were equal with 4 (when fields are separated with whitespaces (awk default FS) ) then print the whole line $0 after we striping the first field $1="" else : print filed#2 $2.

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.