使用 awk、sed 或任何 POSIX 工具替换特定字段

Replacing a specific field using awk, sed or any POSIX tool

我有一个很大的文件 1,其值如下:

a 1
b 2
c 3
d 4
e 5

我还有一个很大的文件2,用冒号分隔,有七个字段如下:

a:2543:2524:2542:252:536365:54654
c:5454:5454:654:54:87:54
d:87:65:1:98:32:87

我想在行中搜索 file1 的变量并替换它在 file2 的第 7 列中的值,因此输出应如下所示:

a:2543:2524:2542:252:536365:1
c:5454:5454:654:54:87:3
d:87:65:1:98:32:4

也许这个 awk 会起作用,假设文件已发布

awk -F: 'NR==FNR{a[]=[=10=];next;}a[]{[=10=]=a[]}1' file1 file2
a:2543:2524:2542:252:536365:1
c:5454:5454:654:54:87:3
d:87:65:1:98:32:4

所以我想出了一个解决办法;最后得到了几行代码。也许有更好的方法 it.But 这行得通!

while read line ; do 
  var1=`echo $line| awk '{print }'`
  var2=`echo $line| awk '{print }'`
  awk -v var1="$var1" -v var2="$var2" -F ':' 'BEGIN { OFS = ":"} ==var1 {sub(".*",var2,)}{print}' file2 > file2.tmp
  mv file2.tmp file2
done < file1
cat file2

这应该可行 - 它假设两个文件都在第一列排序 - 我对与您的解决方案进行非常大的文件的任何性能比较非常感兴趣 - 速度和内存 - --complement 是 linux-特定但如果不可用则很容易替换

file0= #file with single value
file1= #file with 6th value to be replaced
# normalize on colon delimiter
tr ' ' : <$file0|
# join on first field
join -t: $file1 -|
# delete column 7
cut --complement -d: -f7