2017-06-06 2 views
0

Ich habe 2 Dateien - Datei1 & Datei2 mit Inhalt wie gezeigt.ein Feld von seiner Position ausschneiden und in eine andere Position bringen

cat file1.txt 

1,2,3 

cat file2.txt 

a,b,c 

& die gewünschte Ausgabe ist als unten,

a,1,b,2,c,3 

Kann jemand bitte helfen, dies zu erreichen?

Bis jetzt habe ich dies versucht haben,

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

& der Ausgang kam als 1,2,3, a, b, c

Aber mit 'cut' ist nicht der gute Ansatz ich denke, . Becuase hier ich weiß, dass es 3 Werte in beiden Dateien gibt, aber wenn die Werte mehr sind, wird der obige Befehl nicht hilfreich sein.

Antwort

0

Versuch:

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 (eine Nicht-Einzeiler Form einer Lösung zu wie folgt)

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

Paste -d "" Datei * | awk -F,

1 a, '{$ 4" , "$ 1", "$ 5", "$ 2", "$ 6", "$ 3 drucken}' , b, 2, c, 3

Dies ist ein einfacher Druckvorgang. Andere Antworten sind sehr willkommen. Aber wenn die Datei Tausende von Werten enthält, hilft dieser Druckansatz nicht.

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 

oder wenn Sie es vorziehen:

$ 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 
Verwandte Themen