awk - 比较两个文件中的列并替换第一个文件中的文本
awk - Compare columns from two files and replace text in first file
我有两个文件。第一个有 1 列,第二个有 3 列。我想比较两个文件的第一列。如有重合,将第2、3栏替换为具体数值;如果不是,打印同一行。
文件 1:
$ cat file1
26
28
30
文件 2:
$ cat file2
1,a,0
2,a,0
22,a,0
23,a,0
24,a,0
25,a,0
26,r,1510139756
27,a,0
28,r,1510244156
29,a,0
30,r,1510157364
31,a,0
32,a,0
33,r,1510276164
34,a,0
40,a,0
期望的输出:
$ cat file2
1,a,0
2,a,0
22,a,0
23,a,0
24,a,0
25,a,0
26,a,0
27,a,0
28,a,0
29,a,0
30,a,0
31,a,0
32,a,0
33,r,1510276164
34,a,0
40,a,0
我正在使用 gawk
来执行此操作(它在 shell 脚本中,我正在使用 solaris
)但我无法正确输出。它只打印匹配的行:
$fuente="file2"
gawk -v fuente="$fuente" 'FNR==NR{a[FNR]=; next}{print ,="a",="0" }' $fuente file1 > file3
我得到的输出:
$ cat file3
26 a 0
28 a 0
30 a 0
为了清楚起见,真的展开了;像这样调用 (fuente.awk):
awk -F \, -v fuente=file1 -f fuente.awk file2 # -F == IFS
BEGIN {
OFS="," # set OFS to make printing easier
while (getline x < fuente > 0) # safe way; read file into array
{
a[++i]=x # stuff indexed array
}
}
{ # For each line in file2
for (k=1 ; k<=i ; k++) # Lop over array (elements in file1)
{
if ((==a[k]) && (! flag))
{
print(,"a",0) # Found print new line
flag=1 # print only once
}
}
if (! flag) # Not found
{
print([=10=]) # print original
}
flag=0 # reset flag
}
END { }
awk 一行:
awk 'NR==FNR{ a[]; next } in a{ ="a"; =0 }1' file1 FS=',' OFS=',' file2
输出:
1,a,0
2,a,0
22,a,0
23,a,0
24,a,0
25,a,0
26,a,0
27,a,0
28,a,0
29,a,0
30,a,0
31,a,0
32,a,0
33,r,1510276164
34,a,0
40,a,0
我有两个文件。第一个有 1 列,第二个有 3 列。我想比较两个文件的第一列。如有重合,将第2、3栏替换为具体数值;如果不是,打印同一行。
文件 1:
$ cat file1
26
28
30
文件 2:
$ cat file2
1,a,0
2,a,0
22,a,0
23,a,0
24,a,0
25,a,0
26,r,1510139756
27,a,0
28,r,1510244156
29,a,0
30,r,1510157364
31,a,0
32,a,0
33,r,1510276164
34,a,0
40,a,0
期望的输出:
$ cat file2
1,a,0
2,a,0
22,a,0
23,a,0
24,a,0
25,a,0
26,a,0
27,a,0
28,a,0
29,a,0
30,a,0
31,a,0
32,a,0
33,r,1510276164
34,a,0
40,a,0
我正在使用 gawk
来执行此操作(它在 shell 脚本中,我正在使用 solaris
)但我无法正确输出。它只打印匹配的行:
$fuente="file2"
gawk -v fuente="$fuente" 'FNR==NR{a[FNR]=; next}{print ,="a",="0" }' $fuente file1 > file3
我得到的输出:
$ cat file3
26 a 0
28 a 0
30 a 0
为了清楚起见,真的展开了;像这样调用 (fuente.awk):
awk -F \, -v fuente=file1 -f fuente.awk file2 # -F == IFS
BEGIN {
OFS="," # set OFS to make printing easier
while (getline x < fuente > 0) # safe way; read file into array
{
a[++i]=x # stuff indexed array
}
}
{ # For each line in file2
for (k=1 ; k<=i ; k++) # Lop over array (elements in file1)
{
if ((==a[k]) && (! flag))
{
print(,"a",0) # Found print new line
flag=1 # print only once
}
}
if (! flag) # Not found
{
print([=10=]) # print original
}
flag=0 # reset flag
}
END { }
awk 一行:
awk 'NR==FNR{ a[]; next } in a{ ="a"; =0 }1' file1 FS=',' OFS=',' file2
输出:
1,a,0
2,a,0
22,a,0
23,a,0
24,a,0
25,a,0
26,a,0
27,a,0
28,a,0
29,a,0
30,a,0
31,a,0
32,a,0
33,r,1510276164
34,a,0
40,a,0