bash - 如何通过匹配 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",
...
预先感谢您的任何帮助。
解决方案
这可能对您有用(GNU sed):
sed -e '/xxxxxxx\.jpg/R file2' -e '//d' file1
这会将包含xxxxxxx.jpg
的每一行替换为 file2 中的一行。
推荐阅读
- verification - 在dafny中验证条件下的序列和
- android - MaterialDatePicker : 今天如何设置自定义
- c# - 使用 roslyn 在 c# 源代码中查找类引用
- angular - 量角器:为所有 browser.wait 调用设置超时
- c# - 使用 DisplayModeProvider 指定移动视图的 ASP.NET 应用程序启动时要转到的路由
- java - 使用 OR 检查 if 语句中的多个空值并将错误存储在数组中
- typescript - 从对象创建简单的字符串数组
- groovy - 固定小数位 / Java Groovy
- c# - EntityFramework Core 中的数据库更新异常
- c# - 使用 Roslyn 分析器查找 DateTime.Now/Today/UtcNow 的所有用法