2 回答
TA贡献1830条经验 获得超3个赞
以下解决方案可能对您有所帮助,您需要在awknamed变量中提供字段编号fields并可以打印出来。
awk -F, -v fields="1,2,3,4,5,9" 'BEGIN{num=split(fields, array,",")} {for(i=1;i<=num;i++){printf("%s%s",$array[i],i==num?ORS:OFS)}}' OFS=, Input_file
现在也添加非单一衬里形式的解决方案。
awk -F, -v fields="1,2,3,4,5,9" '
BEGIN{
num=split(fields, array,",")}
{
for(i=1;i<=num;i++){
printf("%s%s",$array[i],i==num?ORS:OFS)}}
' OFS=, Input_file
上面的代码说明:
awk -F, -v fields="1,2,3,4,5,9" ' ##Setting field seprator as comma here with -F. Setting variable named fields with values of fields which we need.
BEGIN{ ##Starting BEGIN section here for awk which will be executed before reading the Input_file.
num=split(fields, array,",")} ##using split to split the variable fields into array named array and creating variable num which will have number of element of array.
{
for(i=1;i<=num;i++){ ##Starting a for loop here which starts from variable named i value from 1 to till value of variable num.
printf("%s%s",$array[i],i==num?ORS:OFS)}} ##Printing value of array[i] and then $array[i] will print the field value in current line too. Then checking condition variable i value equal to variable num then print new line else print space with OFS.
' OFS=, Input_file ##Mentioning the Input_file name here.
- 2 回答
- 0 关注
- 352 浏览
添加回答
举报