Bash:用另一个文件的第n行替换匹配的正则表达式 [英] Bash: replace matching regex with nth line from another file

查看:41
本文介绍了Bash:用另一个文件的第n行替换匹配的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件.

一个文件是TXT,包含字符串,每行一个.

File one is a TXT and contains strings, one per line.

第二个文件是一个XML,其中包含多个这样的条目:

File two is a XML with several entries like this:

<data name="Btn:Cancel" xml:space="preserve">
    <value>Cancel</value>
    <comment>Original English: Cancel</comment>
  </data>

我需要用文件一中的相应字符串替换XML文件中的VALUE值:因此,第一次出现的VALUE将被文件中的第一行替换,第二次出现的XML将在文件中的第一行替换替换为文件一的第二行,依此类推.

I need to replace the VALUE value in the XML file with the corresponding string from file one: So the first occurrence of VALUE would be replaced by the first line from the file one, the second occurrence of VALUE in the XML file would be replaced by the second line from file one, and so on.

我已经尝试了几种方法(基本上使用sed),而我的最后一枪是

I've tried several things (basically using sed) and my last shot was

while read line           
do
    echo $count
    echo $line
    sed "s_<value>.*</value>_<value>$line</value>_$count" file.xml > results.xml
    ((count++))
done < file.txt

但是它对results.xml文件没有任何作用:(

But it does nothing on the results.xml file :(

推荐答案

像这样修改您的脚本

count=1
# test.xml is your file
cat test.xml | tr "\n" "\t" > test2.xml
while read line
do
    echo $count
    echo $line
    sed -i " s_<value>[^<]*</value>_<value>$line</value>_${count}; " test2.xml
    ((count++))
done < file.txt
cat test2.xml | tr "\t" "\n" >test3.xml

  • 初始化计数
  • 不同的正则表达式( [^>] * )
  • 使用tr将test.xml转换为单行,带有 number标志 sed s 命令可以使用
  • 使用另一个tr将长行变回
  • 这篇关于Bash:用另一个文件的第n行替换匹配的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆