[英]How to print a column using awk command line and add header
I have a problem and would appreciate any assistance.我有问题,希望得到任何帮助。 I have test1.txt file with the following columns:我有包含以下列的 test1.txt 文件:
column1|column2|column3|column4|column5|column6|column7|column8|
I then run the following to target specific columns.然后我运行以下命令来定位特定列。
cat test1.txt | awk -F "|" '{ print $2, $3, $4, $6, $7}' > teste.csv
The CSV file outputs the result in 1 line like so: CSV 文件在 1 行中输出结果,如下所示:
column2 column3 column4 column6 column7
but what i want is something like但我想要的是像
header2|header3|header4|header6|header7
column2|column3|column4|column6|column7
Would you be able to help me fix the above and - also how can i then add headers after getting the correct result.你能帮我解决上面的问题吗 - 还有我如何在得到正确的结果后添加标题。
Thanks in advance提前致谢
If the problem is that the columns should be separated with |
如果问题是列应该用|
分隔instead of space, you have to set the output field separator OFS
to the same value as the input field separator FS
.而不是空格,您必须将 output 字段分隔符OFS
设置为与输入字段分隔符FS
相同的值。
awk -F "|" -v 'OFS=|' '{ print $2, $3, $4, $6, $7}' test1.txt > teste.csv
You can use the BEGIN
condition to add commands for printing a header. In this case you also can put the assignement to OFS there.您可以使用BEGIN
条件添加用于打印 header 的命令。在这种情况下,您也可以将 OFS 的赋值放在那里。
awk -F "|" 'BEGIN { OFS=FS; print "header2|header3|header4|header6|header7" } { print $2, $3, $4, $6, $7}' test1.txt > teste.csv
With the input shown in the question this prints使用问题中显示的输入打印
header2|header3|header4|header6|header7
column2|column3|column4|column6|column7
Given that you have referenced a csv (comma separated value output in your question), wit th sample data in the file columns, you can run:鉴于您引用了 csv(问题中的逗号分隔值 output),在文件列中包含示例数据,您可以运行:
awk -F\| 'BEGIN { OFS=",";print "COLUMN1"OFS"COLUMN2"OFS"COLUMN3"OFS"COLUMN4"OFS"COLUMN5"OFS"COLUMN6"OFS"COLUMN7"OFS"COLUMN8"OFS } { $1=$1 }1' columns
Set the output to, in the BEGIN section and print the headers required (in the example COLUMN1,COLUMN2 etc) with the new OFS.在 BEGIN 部分将 output 设置为,并使用新的 OFS 打印所需的标题(在示例中为 COLUMN1、COLUMN2 等)。 Then take each line, set $1 to $1 to action a change on $0, taking account of the new OFS.然后在每一行中,将 $1 设置为 $1 以对 $0 执行更改,同时考虑到新的 OFS。 Use 1 to print the new line.使用 1 打印新行。
Output: Output:
COLUMN1,COLUMN2,COLUMN3,COLUMN4,COLUMN5,COLUMN6,COLUMN7,COLUMN8,
column1,column2,column3,column4,column5,column6,column7,column8,
To add the headers添加标题
awk 'BEGIN {print "Column1|Column2|Column3|Column4|Column5|Column6|Column7|Column8"} {print}' table > test1.txt
To add the columns you would like, into the teste.csv要将您想要的列添加到 teste.csv
cat test1.txt| awk -F '|' '{print $2, $3, $4, $6, $7}' > teste.csv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.