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.

8
  • show us your awk command you post that through (eh, minimal please) Commented Jul 6, 2015 at 9: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. Commented Jul 6, 2015 at 9:49
  • ->echo "abc efg hij klm nop qrs uvw" | awk '{ print $6}' qrs ->echo "abc efg hij klm qrs uvw" | awk '{ print $6}' uvw Commented Jul 6, 2015 at 9:53
  • 1
    yes, that's what it does. uvw is the 6th column in case 2, which is expected. Commented Jul 6, 2015 at 9: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? Commented Jul 6, 2015 at 9:57

2 Answers 2

1

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

awk '{print $(NF-1)}' file 
Sign up to request clarification or add additional context in comments.

4 Comments

@ikrabbe Blue Moon is mentioning that he wants to print the penultimate column, so the solution is consistent with that.
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 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.
@BlueMoon all ok, I don't have a problem with your solution but my I like my answer better ;)
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.