bash - 替换分号后的字符串

我有一个包含以下内容的文件 filtered_content:

ip-172-31-42324-162.sa-east-1.compute.internal;2021-06-26T05:07:30Z
ip-172-31-42324-162.sa-east-1.compute.internal;2021-10-12T05:07:30Z
ip-172-31-4234-163.sa-east-1.compute.internal;2021-03-02T05:07:30Z
ip-172-31-4234-163.sa-east-1.compute.internal;2021-05-26T05:07:30Z

和另一个文件 converted_data 内容:

1624684050
1634015250
1614661650
1622005650

我想用 converted_data 的内容替换 filtered_content 中分号后的字符串,如下所示:

ip-172-31-42324-162.sa-east-1.compute.internal;1624684050
ip-172-31-42324-162.sa-east-1.compute.internal;1634015250
ip-172-31-4234-163.sa-east-1.compute.internal;1614661650
ip-172-31-4234-163.sa-east-1.compute.internal;1622005650

我试过类似的方法,但不起作用。

data=$(cat /tmp/converted_data)
cat /tmp/filtered_content | sed 's/;.*//' | sed 's/.${data};//'

最佳答案

您可以考虑这个 awk 解决方案:

awk 'BEGIN{FS=OFS=";"} NR==FNR {arr[FNR]=$1; next} {$2 = arr[FNR]} 1' converted_data filtered_content

ip-172-31-42324-162.sa-east-1.compute.internal;1624684050
ip-172-31-42324-162.sa-east-1.compute.internal;1634015250
ip-172-31-4234-163.sa-east-1.compute.internal;1614661650
ip-172-31-4234-163.sa-east-1.compute.internal;1622005650

更具可读性的形式:

awk '
BEGIN { FS=OFS=";" }
NR == FNR {
   arr[FNR] = $1
   next
}
{
   $2 = arr[FNR]
} 1' converted_data filtered_content

https://stackoverflow.com/questions/67960715/

相关文章:

list - 在 Haskell 中展平列表

perl - 将数组保存到纯文本文件中的问题

sql - 根据列查询找出存储过程

django - 如何在 Django 模板中使用数学余数?

.net - 如何最好地实现脏话处理程序(首选 .NET)?

php - 如何将 URL 参数列表字符串分解为成对的 [key] => [value] 数组?

c++ - 如何在 C++ 中定义可变大小的 vector

sql - 通常,字符串(或varchar)字段用作连接字段吗?

sql - 添加约束以防止 SQL 更新触发器中的重复项

django - Django 模板中的搜索字段