从其位置剪下一个字段并将其置于不同位置
问题描述:
我有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个值,但是如果值更多,上面的命令将不会有帮助。
答
尝试:
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.
答
糊-d “” 文件* | AWK -F, '{打印$ 4" , “$ 1”, “$ 10”, “$ 2”, “$ 6”,“$ 3}'
一个,1 ,b,2,c,3
这是简单的打印操作。其他答案是最受欢迎的。 但是,如果文件包含1000个值,那么这种打印方式将无济于事。
答
$ 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