首页 > 解决方案 > 如何通过匹配 shell/bash 脚本中的不同文件来替换 for 循环语句

问题描述

使用我的 shell 脚本,我试图匹配 2 个不同的文件,并将 File1 中的出现替换为 File2 的行:

File1 occurency 1 <-- File2 row 1
File1 occurency 2 <-- File2 row 2
File1 occurency 3 <-- File2 row 3
...

文件 2 中的行数等于文件 1 中的出现次数,因为最初它们取自文件 1

File1 - 是一个 Json 文件

...
"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

File2 - 是一个格式化的“json like”文件

"profilePhoto":"https://someurl.ltd/aaaa_90.jpg"
"profilePhoto":"https://someurl.ltd/bbbb_90.jpg"
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
 ....

实际上,必须完成这项工作的脚本部分看起来像

IFS=$'\n'
set -f
for i in $(cat < File2.txt); do

sed -i "s|.*social.*|$i|g" File1.json

done

此脚本将 File1 中的所有出现替换为 File2 的第一行,因此在第二个循环中找不到更多匹配项。输出示例

...
"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

我需要这样的输出

...
"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**aaaa**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**bbbb**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

预先感谢您的任何帮助。

标签: bashshellsed

解决方案


这可能对您有用(GNU sed):

sed -e '/xxxxxxx\.jpg/R file2' -e '//d' file1

这会将包含xxxxxxx.jpg的每一行替换为 file2 中的一行。


推荐阅读