【问题标题】:How can I add or remove character from a specified line number in shell?如何在 shell 的指定行号中添加或删除字符?
【发布时间】:2016-08-10 04:55:19
【问题描述】:

我有一个文件,我必须多次迭代,每次都用 python 运行它。如何从 shell 的特定行中删除或添加字符?

例如文件 ex.file,

$ cat ex.file
stuff
more stuff
more stuff
more stuff
#<- remove this character
<-add a pund sign here
more stuff
more stuff

我想要的输出是:

$ cat ex.file
stuff
more stuff
more stuff
more stuff
<- remove this character
#<-add a pund sign here
more stuff
more stuff

【问题讨论】:

    标签: bash shell unix sed


    【解决方案1】:

    在第 6 行的开头添加 #:

    sed '6 s/^/#/' ex.file
    

    要从第 5 行删除前导 #:

    sed '5 s/^#//' ex.file
    

    【讨论】:

    • 如何将 sed 定向到 ex.file
    • @kilojoules:查看我的编辑。您可以使用sed -i 而不是仅使用sed 来编辑文件,也可以将其写入新文件,例如sed ... &gt; newfile
    • 非常感谢!如何覆盖ex.file
    • @kilojoules:我刚刚告诉过你。
    • @kilojoules 您可以一次调用sed -i -e '5 s/^#//' -e '6 s/^/#/' ex.file 完成所有操作,并添加-i.bak 以在ex.file.bak 中的原始文件上创建备份。
    【解决方案2】:

    Oneliner awk 版本从第 5 行删除 # 并将 # 添加到第 6 行。

    awk 'NR==5 {sub(/^#/,"") } NR==6 { sub(/^/,"#")}1' infile
    

    【讨论】:

      猜你喜欢
      • 2022-10-23
      • 2019-05-15
      • 2013-07-04
      • 2013-03-02
      • 2015-03-13
      • 1970-01-01
      • 2014-05-05
      • 2021-08-17
      • 2017-10-10
      相关资源
      最近更新 更多