【发布时间】:2021-10-18 00:03:39
【问题描述】:
假设我在/train/xml/ 中有数百个*.xml,格式如下
# this is the content of /train/xml/RIGHT_NAME.xml
<annotation>
<path>/train/img/WRONG_NAME.jpg</path> # this is the WRONG_NAME
</annotation>
<path>...</path> 中的文件名 WRONG_NAME 应该与 .xml 文件的名称匹配,因此它看起来像这样:
# this is the content of /train/xml/RIGHT_NAME.xml
<annotation>
<path>/train/img/RIGHT_NAME.jpg</path> # this is the **RIGHT_NAME**
</annotation>
我能想到的一个解决方案是:
1。将所有文件名导出到文本文件中:
ls -1 *.xml > filenames.txt
生成一个包含内容的文件:
RIGHT_NAME_0.xml
RIGHT_NAME_1.xml
...
2。然后编辑filenames.txt,使其变为:
# tab at beginning of each line
<path>/train/img/RIGHT_NAME_0.jpg</path>
<path>/train/img/RIGHT_NAME_1.jpg</path>
...
3。然后,将nth .xml 文件的第三行替换为来自filenames.txt 的nth 行。
因此是问题的标题。
我已经尝试过sed和awk,但没有成功。我应该怎么做(在 EDIT: MacOS 机器上)?另外,有没有更优雅的解决方案?
提前感谢您的帮助!
---我尝试过的事情(但没有成功)---
# this replaces the fifth line with an empty string
for i in *.xml ; do perl -i.bak -pe 's/.*/$i/ if $.==5' RIGHT_NAME.xml ; done
# this apprehends contents of filenames.txt after third line
sed -i.bak -e '/\<path\>/r filenames.txt' RIGHT_NAME.xml
# also, trying to utilize the <path>...</path> pattern...
【问题讨论】:
-
我反复尝试了
sed和awk,但没有成功。。你能分享一些你尝试过的具体例子吗?在我看来,如果您设置了文件搜索并匹配名称,那么您可以使用sed -i使用匹配名称的基础来修改文件。混入单个文件是一种不太理想的方法。 -
嘿,真快!到目前为止,我得到的最接近的是:
sed -i.bak -e '/\<path\>/r filenames.txt' RIGHT_NAME.xml,它在第三行之后理解了filenames.txt的内容......