Linux 如何使用 AWK 选择一些列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8973450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:10:27  来源:igfitidea点击:

How to select some columns with AWK?

linuxawk

提问by mahmood

I want to select some columns in a file and run some command on it. so my script is this

我想在文件中选择一些列并在其上运行一些命令。所以我的脚本是这样的

awk '{print ,,,,,,,,,,,,,,,}' test.txt > outpot.txt

but this print it to another file and I tried to do this

但这将它打印到另一个文件,我试图这样做

awk '{print ,,,,,,,,,,,,,,}' test.txt | next commands

(This commands works fine! I did a mistake and I don't know how to remove this question)

(这个命令工作正常!我犯了一个错误,我不知道如何删除这个问题)

is it possible to make this command shorter like instead of writing all columns just write $1-7 && $9-15 && $19(but this is not really important I just wondered if it's possible). The main thing is to be able to choose that columns

是否可以使这个命令更短,而不是像写所有列那样写$1-7 && $9-15 && $19(但这并不重要,我只是想知道是否可能)。最主要的是能够选择那些列

采纳答案by jaypal singh

Updated based on glennHymanman'ssuggestion:

根据glennHymanman 的建议更新:

awk '{for (i=1;i<=NF;i++) if ((1<=i && i<=7) || (9<=i && i<=15) || i==19) printf("%s ", $i); print ""}' file

回答by anubhava

To answer one part of your question, in awk script you can do:

要回答您的问题的一部分,您可以在 awk 脚本中执行以下操作:

{
   for (i=1; i<=7; i++)
      print $i;
   for (i=9; i<=15; i++)
      print $i;
   print ;
}