0

What we have to do if input is variable each time and on the bases of that input we have to again make another operation on that output of first command. please refer below example.

suppose I executed x command on terminal and it gives me output as below (space separated):

abc efg hij klm nop qrs uvw
abc efg hij klm qrs uvw

Sometimes there are 6 columns and sometimes there are 5 columns.

I pipe this output to awk command to print the 6th column i.e. qrs, it returns the correct result in the 1st case but in second case it shows uvw.

Thor
  • 45,082
  • 11
  • 119
  • 130
  • show us your awk command you post that through (eh, minimal please) – ikrabbe Jul 06 '15 at 09:43
  • What in case 2 the expected output is? What should your awk command actually do? It seems working fine, in both cases it prints the 6th column: "qrs" in case 1 and uvw in case 2 are actually both the 6th field. – il_raffa Jul 06 '15 at 09:49
  • ->echo "abc efg hij klm nop qrs uvw" | awk '{ print $6}' qrs ->echo "abc efg hij klm qrs uvw" | awk '{ print $6}' uvw – navnath bagade Jul 06 '15 at 09:53
  • 1
    yes, that's what it does. `uvw` is the 6th column in `case 2`, which is expected. – ikrabbe Jul 06 '15 at 09:55
  • @navnathbagade You haven't stated how to identify "qrs" that you want. Is it the penultimate column or something else? i.e. If the command gives different number of columns as output, how do you identify the column you want? – P.P Jul 06 '15 at 09:57
  • I am not able to add image , It will clear whole idea – navnath bagade Jul 06 '15 at 10:12
  • actually, in second case there are spaces in between klm and qrs – navnath bagade Jul 06 '15 at 10:12
  • @navnathbagade: By default awk treats spaces and tabs equally, so that is not your problem. Could you post a sample input file somewhere? – Thor Jul 06 '15 at 12:50

2 Answers2

1

If you want the last but one column then you can use of NF variable:

awk '{print $(NF-1)}' file
P.P
  • 117,907
  • 20
  • 175
  • 238
  • @ikrabbe Blue Moon is mentioning that he wants to print the penultimate column, so the solution is consistent with that. – fedorqui Jul 06 '15 at 09:48
  • yes, I already removed my comment. But I don't know if Op really wants to print the penultimate column. Also $(NF-1) breaks on emtpy lines. – ikrabbe Jul 06 '15 at 09:49
  • @ikrabbe That's what I think based on the example given. There must some sort of pattern (last column, or 3rd from last etc) to uniquely identify the desired column. Otherwise, how can anyone know what to extract? If that's not the case, OP should clarify it. – P.P Jul 06 '15 at 09:51
  • @BlueMoon all ok, I don't have a problem with your solution but my I like my answer better ;) – ikrabbe Jul 06 '15 at 09:53
0

See this awk and the output!

awk '{print NF, $NF, $6}' <<EOF
abc efg hij klm nop qrs uvw
abc efg hij klm qrs uvw
EOF

awk starts counting from 1, so everything is correct.

ikrabbe
  • 1,909
  • 12
  • 25