用awk打印第一列第二列其后每隔一个3列并打印匹配标准的行 [英] Use awk to print first column, second column and one every 3 columns thereafter and print only rows matching criteria
问题描述
我试图让AWK打印的第一列,第二列,一列,每4,经过(如1,2,6,10等)。我也想删除第二行,因为这是一些无关紧要的东西,一个头。最后,我想基于第一列(字符串形式的载体提供)的值过滤行。
I'm trying to get awk to print the first column, second column and one column every 4 after that (Eg. 1,2,6,10, etc). I also want to remove the second row because this is a header with unimportant stuff. Lastly, I want to filter rows based on the value of the first column (supplied as a vector of strings).
让我们这个例子中,说我只想要匹配行'表'或'椅子':
Let's take this example, and say I only want rows matching 'table' or 'chair':
string number1 junk1 junk2 junk3 number2 junk4 junk5 junk6 number3
junk7 junk8 junk9 junk10 junk11 junk12 junk13 junk14 junk15 junk16
car 7 x1 x5 x9 3 x13 x17 x21 11
table 8 x2 x6 x10 5 x14 x18 x22 2
chair 9 x3 x7 x11 4 x15 x19 x23 6
comb 0 x4 x8 x12 1 x16 x20 x24 10
我想有这个作为输出
I would want to have this as output
string number1 number2 number3
table 8 5 2
chair 9 4 6
感谢
推荐答案
如果您的列被限制为10
If your columns are limited to 10
awk 'BEGIN{OFS="\t"} NR!=2 && /table/ || /chair/ || NR==1{print $1,$2,$6,$10}'
如果列数不知道,或者太多列举你可以做到这一点。
if column count is not known, or too many to enumerate you can do this.
awk 'BEGIN{OFS="\t"} NR!=2 && /table/ || /chair/ || NR==1{line=$1 OFS $2; for(i=6;i<=NF;i+=4)line=line OFS $i; print line}'
您也可以外部化过滤到一个变量,如
you can also externalize the filter into a variable, such as
awk -v filter="chair table" 'BEGIN{OFS="\t"} NR==1 || (NR!=2 && (filter ~ $1)) {line=$1 OFS $2; for(i=6;i<=NF;i+=4)line=line OFS $i; print line}'
这篇关于用awk打印第一列第二列其后每隔一个3列并打印匹配标准的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!