2017-06-06 64 views
0

我有2個文件 - file1 & file2,其內容如圖所示。從其位置剪下一個字段並將其置於不同位置

cat file1.txt 

1,2,3 

cat file2.txt 

a,b,c 

&所需的輸出是如下,

a,1,b,2,c,3 

任何人都可以請幫助實現這一目標?

到現在我都試過,

paste -d "," file1.txt file2.txt|cut -d , -f4,1,5,2,6,3 

&輸出來爲1,2,3,A,B,C

但使用 '切割' 是不是好辦法,我認爲。 因爲我知道在這兩個文件中都有3個值,但是如果值更多,上面的命令將不會有幫助。

回答

0

嘗試:

awk -F, 'FNR==NR{for(i=1;i<=NF;i++){a[FNR,i]=$i};next} {printf("%s,%s",a[FNR,1],$1);for(i=2;i<=NF;i++){printf(",%s,%s",a[FNR,i],$i)};print ""}' file2.txt file1.txt 

OR(的解決方案NON-一個班輪形式太如下)

awk -F, 'FNR==NR{      ####making field separator as , then putting FNR==NR condition will be TRUE when first file named file1.txt will be read by awk. 
     for(i=1;i<=NF;i++){   ####Starting a for loop here which will run till the total number of fields value from i=1. 
     a[FNR,i]=$i     ####creating an array with name a whose index is FNR,i and whose value is $i(fields value). 
          }; 
     next       ####next will skip all further statements, so that second file named file2.txt will NOT read until file1.txt is completed. 
       } 
       { 
     printf("%s,%s",a[FNR,1],$1); ####printing the value of a very first element of each lines first field here with current files first field. 
     for(i=2;i<=NF;i++){   ####starting a for loop here till the value of NF(number of fields). 
     printf(",%s,%s",a[FNR,i],$i) ####printing the values of array a value whose index is FNR and variable i and printing the $i value too here. 
          }; 
     print ""      ####printing a new line here. 
       } 
     ' file2.txt file1.txt   ####Mentioning the Input_files here. 
0

糊-d 「」 文件* | AWK -F, '{打印$ 4" , 「$ 1」, 「$ 10」, 「$ 2」, 「$ 6」,「$ 3}'

一個,1 ,b,2,c,3

這是簡單的打印操作。其他答案是最受歡迎的。 但是,如果文件包含1000個值,那麼這種打印方式將無濟於事。

0
$ awk ' 
    BEGIN { FS=OFS="," } 
    NR==FNR { split($0,a); next } 
    { 
     for (i=1;i<=NF;i++) { 
      printf "%s%s%s%s", $i, OFS, a[i], (i<NF?OFS:ORS) 
     } 
    } 
' file1 file2 
a,1,b,2,c,3 

或者如果你喜歡:

$ paste -d, file2 file1 | 
awk ' 
    BEGIN { FS=OFS="," } 
    { 
     n=NF/2 
     for (i=1;i<=n;i++) { 
      printf "%s%s%s%s", $i, OFS, $(i+n), (i<n?OFS:ORS) 
     } 
    } 
' 
a,1,b,2,c,3 
相關問題