awk for unexpected result

Viewed 70

Hello guys i have this format document.

id first_name last_name age address telephone item1 tax1 item2 tax2 item3 tax3

And i need this result

id first_name last_name age address telephone item1 tax1  
id first_name last_name age address telephone item2 tax2  
id first_name last_name age address telephone item3 tax3

use this command with awk

awk '{for (i=5; i<NF; i+=2) print $1, $2, $3, $4, $5, $6, $i, $(i+1)}' file.txt > file2.txt

and this unexpected result

id first_name last_name age address telephone address telephone 
id first_name last_name age address telephone item1 tax1 
id first_name last_name age address telephone item2 tax2 
id first_name last_name age address telephone item3 tax3

I would appreciate if you help me please.

1 Answers

To get the code to work, you need to note which field ID you need to start iterating from. In this case, it is Field 7. Then, you may start "splitting" the data the way you need:

awk '{for (i=7; i<NF; i+=2) print $1, $2, $3, $4, $5, $6, $i, $(i+1)}' file.txt > file2.txt

See the online demo:

#!/bin/bash
s='id first_name last_name age address telephone item1 tax1 item2 tax2 item3 tax3'
awk '{for (i=7; i<NF; i+=2) print $1, $2, $3, $4, $5, $6, $i, $(i+1)}' <<< "$s"

Output:

id first_name last_name age address telephone item1 tax1
id first_name last_name age address telephone item2 tax2
id first_name last_name age address telephone item3 tax3
Related