【发布时间】:2021-04-27 22:45:30
【问题描述】:
我有两个文件:masterlist.txt 包含数百行 URL,toupdate.txt 包含 masterlist.txt 文件中需要替换的少量更新版本的行。
我希望能够使用 Bash 自动执行此过程,因为这些列表的创建和使用已经在 bash 脚本中进行。
URL 的服务器部分是变化的部分,因此我们可以使用唯一部分进行匹配:/whatever/whatever_user.xml,但是如何查找和替换 masterlist.txt 中的那些行?即如何遍历toupdate.txt 的每一行,并在它以/f_SomeName/f_SomeName_user.xml 结尾时,找到以masterlist.txt 结尾的那一行并将整行替换为新行?
例如,https://123456url.domain.com/26/path/f_SomeName/f_SomeName_user.xml 变为 https://new-123.domain.com/1/path/f_SomeName/f_SomeName_user.xml。
masterlist.txt 的其余部分需要保持原样,因此我们必须只查找和替换具有相同行尾 (ID) 的不同服务器的行。
结构
masterlist.txt 看起来像这样:
https://123456url.domain.com/26/path/f_SomeName/f_SomeName_user.xml
https://456789url.domain.com/32/path/f_AnotherName/f_AnotherName_user.xml
https://101112url.domain.com/1/path/g_SomethingElse/g_SomethingElse_user.xml
https://222blah11.domain.com/19/path/e_BlahBlah/e_BlahBlah_user.xml
[...]
toupdate.txt 看起来像这样:
https://new-123.domain.com/1/path/f_SomeName/f_SomeName_user.xml
https://foo-254.domain.com/8/path/g_SomethingElse/g_SomethingElse_user.xml
期望的结果
使masterlist.txt 看起来像:
https://new-123.domain.com/1/path/f_SomeName/f_SomeName_user.xml
https://456789url.domain.com/32/path/f_AnotherName/f_AnotherName_user.xml
https://foo-254.domain.com/8/path/g_SomethingElse/g_SomethingElse_user.xml
https://222blah11.domain.com/19/path/e_BlahBlah/e_BlahBlah_user.xml
[...]
初步检查
我查看了sed,但我不知道如何使用这两个文件中的行进行查找和替换?
这是我目前所拥有的,至少在处理文件:
#!/bin/bash
#...
while read -r line; do
# there's a new link on each line
link="${line}"
# extract the unique part from the end of each line
grabXML="${link##*/}"
grabID="${grabXML%_user.xml}"
# if we cannot grab the ID, then just set it to use the full link so we don't have an empty string
if [ -n "${grabID}" ]; then
identifier=${grabID}
else
identifier="${line}"
fi
## the find and replace here? ##
# we're done when we've reached the end of the file
done < "masterlist.txt"
【问题讨论】:
标签: bash awk sed replace file-io