【问题标题】:Unix command to insert a comment on the top of all files in a directoryUnix命令在目录中所有文件的顶部插入注释
【发布时间】:2013-01-11 22:50:02
【问题描述】:

我想为 Unix 目录中的所有文件添加注释。如果有任何我可以使用的命令组合,请提出解决方案。

【问题讨论】:

    标签: linux file shell unix find


    【解决方案1】:

    尝试使用简单的shell 连接:

    for i in *; do
        { echo '# this is a comment'; cat "$i"; } > /tmp/_$$file &&
        mv /tmp/_$$file "$i"
    done
    

    【讨论】:

      【解决方案2】:

      使用findsed

      $ find . -maxdepth 1 -type f -exec sed -i '1i #comment' {} \;
      

      这会将#comment这一行添加到当前目录中所有文件的顶部

      【讨论】:

      • 或将\; 替换为+ 以在一次sed 调用中处理多个文件。
      【解决方案3】:

      为了好玩,请尝试使用

      echo $'1i\n# comment\n.\nw\nq' | ed -s file.txt 
      

      Here-doc 版本:

      ed -s file.txt <<EOF
      1i
      # comment
      .
      w
      q
      EOF
      

      【讨论】:

        【解决方案4】:

        如果您想为所有带有扩展名的文件添加注释(例如“.rb”):

        find . -maxdepth 1 -type f -name "*.rb" -exec sed -i '1i #comment' {} \;
        

        和递归:

        find . -type f -name "*.rb" -exec sed -i '1i #comment' {} \;
        

        【讨论】:

          猜你喜欢
          • 2016-07-04
          • 2018-07-12
          • 2017-04-05
          • 2012-10-06
          • 2013-03-06
          • 2012-05-18
          相关资源
          最近更新 更多