【问题标题】:Replace line in text file with line from other text file将文本文件中的行替换为其他文本文件中的行
【发布时间】:2014-11-18 12:35:43
【问题描述】:

我的问题是以下问题的变体:

bash: replace an entire line in a text file

问题是用给定的字符串(替换行)替换文件的第 N 行。就我而言,我不能只键入替换行,而是必须从另一个文件中读取它。

例如:

文本文件1:

my line
your line
his line
her line

文本文件2:

our line

我想用 textfile2 中的行替换 textfile1 的第二行。

我以为我可以阅读 textfile2

while IFS= read SingleLine 

等等。然后使用$SingleLine 作为替换行,但我失败了......取决于我使用的引号类型(请原谅我的无知......)我最终用文本替换了有问题的行 $SingleLine 或使用 SingleLine 或只是收到错误消息:-[

我相信你可以帮助我!!

编辑解决方案: 我选择了小改动的内联解决方案

sed '2d;1r textfile2' textfile1 > newfile1 

要替换第 N 行,解决方案是(有关解释,请参阅 cmets on接受的解决方案)

sed 'Nd;Mr textfile2' textfile1 > newfile1 

N 为所需的行号,M=N-1。

谢谢大家!

【问题讨论】:

    标签: bash replace


    【解决方案1】:

    我会使用 sed 解决方案 anubhava 发布。这是bash 中的一个替代方案。

    #!/bin/bash
    
    while read -r line; do 
        (( ++linenum == 2 )) && while read -r line; do 
            echo "$line"
            continue 2    # optional param to come out of nested loop
        done < textfile2
        echo "$line"; 
    done < textfile1
    

    或使用awk

    awk 'FNR==2{if((getline line < "textfile2") > 0) print line; next}1' textfile1
    

    【讨论】:

      【解决方案2】:

      是这个脚本还是直接来自终端? 如果这是一个脚本。您可以尝试将文件 2 存储到变量中 fromfile2=$(cat textfile2) 然后将您的 textfile1 替换为 sed -i "s/your line/$fromfile2"。 希望对您有所帮助。

      【讨论】:

      • 谢谢!我忘了指定我也不能输入原始文件的第二行。那我写什么而不是上面的“你的行”?我试过 sed "2s/*/$fromfile2 textfile1 > textfile1new 但它没有用(“正则表达式中的未终止替换”)。
      【解决方案3】:

      使用sed

      sed '2d;1r file2' file1
      my line
      our line
      his line
      her line
      

      进行内联编辑:

      sed -i.bak '2d;1r file2' file1
      

      【讨论】:

      • 谢谢!但是......你能解释一下'2d;1r'部分吗?特别是:如果我想替换第 4 行怎么办?!
      • 2d 正在删除第 2 行,1r file2 在第 1 行末尾替换 file2 内容。要替换第 4 行,请使用:sed '4d;3r file2' file1
      • 太棒了!谢谢,真的很快! :-) 我采用了小改动sed '2d;1r textfile2' textfile1 &gt; newfile1 的内联解决方案来保存新文件而不破坏原始文件。
      猜你喜欢
      • 2021-03-24
      • 2012-03-19
      • 2017-06-06
      • 1970-01-01
      • 2016-08-08
      相关资源
      最近更新 更多