2 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊
以下解決方案可能對(duì)您有所幫助,您需要在awknamed變量中提供字段編號(hào)fields并可以打印出來(lái)。
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
現(xiàn)在也添加非單一襯里形式的解決方案。
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
上面的代碼說(shuō)明:
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.
添加回答
舉報(bào)