using the $1 $2 etc for words in awk

So if I have an awk statement that is basically just looking at the NF at if its more than 2, then print out the first 2 words, and all the rest on another line. I know that $1 and $2 are the first two fields, but how would I symbolise telling it to print all the other fields regardless of how many there are on a newline?

Just some quick pseudocode as im away from my PC

if (NF>2){
print $1 FS $2 "\n" 
}

now after the \n I want to know how i can tell it to print out all the other fields, bearing in mind that the number of fields it checks on each line can vary.
Many thanks

awk 'NF > 2 {
  for (i = 0; ++i <= NF;)
    printf "%s", ($i (i == 2 ? RS : FS))
  print x
  }' infile  
1 Like

Hi.

You could use a for-loop:

for( i = 3; i <= NF; i++ ) ...

Or, perhaps:

$ echo 1 2 3 4 5 6 | awk '{if( NF > 2) { $3 = RS $3}}1'
1 2
3 4 5 6
2 Likes

If I got you correctly,Try:

awk 'NF>2 { print $1" "$2; $1=$2=""; print; }' file
1 Like

Nice :slight_smile:

Hi Rad,
I am new to awk,
Pls tell me what does mean by 1 at end in your code

echo 1 2 3 4 5 6 | /usr/xpg4/bin/awk '{if( NF > 2) { $3 = RS $3}}1'

This is scottn's code, not mine.
The 1 simply means true, which in the pattern/expression part causes the execution of the default action, which is print the current record.

Thanks man but one query that only print is a default command or any thing else?

Good stuff, but I actually need this printing stuff in an else if in my script, and I have about 3 else if's, and just substituting the command into it doesn't work! Could you show me how you would do it?

I have something like:

/usr/bin/nawk '
{if ( NF>2 ){
     if ($3 ~/and/){
         print $0}
    if ($3 ~/do/){
        print $0}}
else if ($3 ~/and/){
        {$4 = RS $4}}1
else if ($3 ~/do/){
        {$4 = RS $4}}1
else if ($3 ~/\./){
        {$3 = RS $3}}1
 
}
 
else{
print $0}
 
}' filename.txt

NOTE: im using Solaris

PLEASE HELP! thanks!

Hi.

Originally I posted:

$ echo 1 2 3 4 5 6 | awk '{if( NF > 2) { $3 = RS $3; print} }'

but changed it. Maybe that is closer to what you needed?

I have to be honest... I don't fully understand your logic (and overuse of curly brackets!), but this is what I think you were looking for:

/usr/bin/nawk '{
  if ( NF>2 ) {
    if ( ($3 ~ /and/) || ($3 ~ /do/) )
      $4 = RS $4
    else if ($3 ~ /\./)
      $3 = RS $3
    print
  } else
    print
}' filename.txt


Neither do i! as they say, im "yung and lernin". but thanks anyway, from your solution I managed to work it out all on my own (with a bit of your help though ofcourse!)

:smiley:

Nice one!