我有一堆文件比字段名称有更多的值(不必要的值),而且我还有一个我希望保留的标题。
例如,使用包含以下内容的test_awk.txt文件
My header is here
it can have several lines
data1 data2 data3
1,2,3,4
2,3,4,5
我想要的是以下内容:
My header is here
it can have several lines
data1,data2,data3
1,2,3
2,3,4
我尝试使用简单的awk命令,但只能抑制整个文件的列。因此,删除我的标题,最重要的是,删除最后一个字段名称:
awk 'BEGIN{FS=OFS=","}NR>2{NF--;print}' test_awk.txt
给出:
data1,data2
1,2,3
2,3,4
答案 0 :(得分:2)
关注awk
可能对您有帮助。
awk -F' |,' '/^data/{val=NF;} /^[0-9]/ && NF>val{NF=val} 1' OFS=, Input_file
输出如下。
My header is here
it can have several lines
data1 data2 data3
1,2,3
2,3,4
说明: 此处还添加了非单一的班轮表格,并附上说明:
awk -F' |,' ' ##Making field separator as space or comma for each line of Input_file here.
/^data/{ ##Checking condition here if a line is starting from string data, if yes then do following:
val=NF; ##Creating variable named val and its value is value of the number of fields on current line of Input_file.
}
/^[0-9]/ && NF>val{ ##Checking condition here if any line starts from digits and value of current NF is greater than variable val then do following:
NF=val ##Assigning the value of NF to variable named val here.
}
1 ##Mentioning 1 here will make sure I we are making condition TRUE here and not mentioning any action here so by default print of current line will happen as an action.
' OFS=, Input_file ##Setting OFS(output field separator) as comma here and mentioning Input_file here.
答案 1 :(得分:2)
$ awk 'BEGIN{FS=OFS=","} NR>3{NF--} 1' test_awk.txt
My header is here
it can have several lines
data1 data2 data3
1,2,3
2,3,4
表示如果NR> 3,则更改NF并打印..所以这会错过打印行NR< = 3
NR>3{NF--}
1
仅更改行号的字段数> 3 $0
以惯用方式打印sed
您也可以使用$ sed '4,$ s/,[^,]*$//' test_awk.txt
My header is here
it can have several lines
data1 data2 data3
1,2,3
2,3,4
4,$
s/,[^,]*$//
替换仅适用于这些行 - 即行号&gt; 3 #include<iostream>
using namespace std;
int main()
{
cout<<"HELLOW WORLD";
return 0;
}
删除最后一个字段