大家好,我有这个格式的文档。
id first_name last_name age address telephone item1 tax1 item2 tax2 item3 tax3
我需要这个结果
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
使用awk
awk '{for (i=5; i<NF; i+=2) print $1, $2, $3, $4, $5, $6, $i, $(i+1)}' file.txt > file2.txt
和这个意想不到的结果
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
如果你能帮助我,我会很感激的。
要使代码工作,您需要注意需要从哪个字段ID开始迭代。在这种情况下,它是7号场。然后,你可能会开始"分裂"。您需要的数据:
awk '{for (i=7; i<NF; i+=2) print $1, $2, $3, $4, $5, $6, $i, $(i+1)}' file.txt > file2.txt
查看在线演示:
#!/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"
输出:
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