从它的位置切割一个字段&将它放在不同的位置

时间:2017-06-06 17:44:10

标签: shell awk

我有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

但是使用' cut'我认为不是好方法。 因为我知道这两个文件中有3个值,但如果值更多,则上面的命令将没有用。

3 个答案:

答案 0 :(得分:0)

粘贴-d“,”文件* | awk -F,'{print $ 4“,”$ 1“,”$ 5“,”$ 2“,”$ 6“,”$ 3}“

A,1,B,2,C,3

这是简单的打印操作。其他答案非常受欢迎。 但是如果文件包含1000的值,那么这种打印方法将无济于事。

答案 1 :(得分: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(非单一衬里形式的溶液也如下)

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.

答案 2 :(得分: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