6

I have an input file :

A 123 name: 1 AAA  
B 123 name: 2 AAA name: 3 BBB  
C 234 name: 1 AAA name: 2 BBB name: 5 CCC 

If the column is 'name:', I want to print the next and the next column.

This is my awk code:

cat input.txt | awk '{for(i=1;i<=NF;i++)if($i == "name:")print $(i+1),$(i+2)}'

But, in this case, all columns are listed in a line like this:

1 AAA  
2 AAA  
3 BBB  
1 AAA  
2 BBB  
5 CCC

I want the columns to be printed like this:

1 AAA  
2 AAA 3 BBB    
1 AAA 2 BBB 5 CCC
1
  • Try with: awk '{for (i=1; i<=NF-3; i++) $i = $(i+3); NF-=3; print}' inputfile | sed -e 's/name: //g' However, as reading again the question, it seems that there is the possibility that not all the columns have the same format (I understand that may be some lines which don't have 'name:' column), isn't it? Jan 24, 2017 at 9:44

1 Answer 1

7

Just replace print with printf to print the value on the same line, and insert new line after finishing the iteration on the the line:

awk '{{for(i=1;i<=NF;i++)if($i == "name:") printf $(i+1)" "$(i+2)" "} print ""; }' yourfile

The output:

1 AAA 
2 AAA 3 BBB 
1 AAA 2 BBB 5 CCC

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.