【问题标题】:Bourne Shell : How to insert some lines of text to a given line number of a fileBourne Shell:如何将一些文本行插入文件的给定行号
【发布时间】:2011-02-11 04:18:12
【问题描述】:

我正在编写一个 Bourne Shell 脚本来自动编辑源文件。

我得到我需要的行号是这样的:

line=`sed -n '/#error/=' test.h`
line=$[$line - 2]

现在我想在这个行号后面插入几行文本,我该怎么做?

【问题讨论】:

    标签: sed sh


    【解决方案1】:

    看来你工作太辛苦了。为什么不直接插入文本而不是查找行号?例如:

    $ sed '/#错误/a\ > 此文本已插入 > ' 测试.h

    如果要插入的文本在文件中,那就更简单了:

    $ sed '/#error/r 文件名' test.h

    【讨论】:

      【解决方案2】:

      你可以只使用 awk

      awk '/#error/{for(i=1;i<=NR-2;i++){print _[i]}print "new\n"_[NR-1];f=1 }!f{_[NR]=$0 }f' file > t && mv t file
      

      【讨论】:

        【解决方案3】:
        line=$(sed -n '/#error/=' test.h)
        line=$(($line - 2))
        sed -i "$line s/$/\ntext-to-insert/" test.h
        

        sed -i "$line r filename" test.h
        

        【讨论】:

          【解决方案4】:

          如果你安装了简单的 unix 编辑器ed,你可以这样说:

          echo "$line i
          $lines
          .
          w
          q
          " | ed filename.txt
          

          这是没有“视觉”模式的 vi。 $line 必须是行号,$lines 必须是要插入文件的文本。

          【讨论】:

            【解决方案5】:
            totallines=`cat test.h | wc -l`
            head -n $line test.h >$$.h
            echo "some text" >>$$.h
            tail -n $((totallines-line)) test.h >>$$.h
            mv $$.h head.h
            

            ?
            (更正)

            【讨论】:

              猜你喜欢
              • 2013-03-02
              • 2017-04-23
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-01-24
              • 1970-01-01
              • 2016-06-06
              • 2017-12-07
              相关资源
              最近更新 更多