【问题标题】:Linux command to replace set of lines for a group of files under a directoryLinux命令替换目录下一组文件的行集
【发布时间】:2023-03-21 14:46:01
【问题描述】:

我需要替换只选择的250个erlang文件(扩展名为.erl)的前4个标题行,但是目录+子目录中总共有400个erlang文件,我需要避免修改不需要的文件改变。 我有要修改的文件名列表,但不知道如何让我的 linux 命令使用它们。

sed -i '1s#.*#%% This Source Code Form is subject to the terms of the Mozilla Public#' *.erl
sed -i '2s#.*#%% License, v. 2.0. If a copy of the MPL was not distributed with this file,#' *.erl
sed -i '3s#.*#%% You can obtain one at http://mozilla.org/MPL/2.0/.#' *.erl
sed -i '4s#.*##' *.erl

在上面的命令中,我不是传递*.erl,而是传递那些我需要修改的文件名列表,一一完成需要3天以上的时间。

有什么办法吗?

【问题讨论】:

    标签: linux unix sed file-handling


    【解决方案1】:

    您可以将 sed c(用于更改)命令应用于列表中的每个文件:

    while read file; do
      sed -i '1,4 c\
    %% This Source Code Form is subject to the terms of the Mozilla Public\
    %% License, v. 2.0. If a copy of the MPL was not distributed with this file,\
    %% You can obtain one at http://mozilla.org/MPL/2.0/.\
    
    ' "$file"
    done < filelist
    

    【讨论】:

      【解决方案2】:

      不回答您的问题,而是提出改进建议。用于替换标头的四个sed 命令效率低下。我会将新标头写入文件并执行以下操作

      sed -i -e '1,3d' -e '4{r header' -e 'd}' file
      

      将文件的前四行替换为标题。

      您当前的 s### 方法的另一个问题是您必须在要替换的文本中注意特殊字符 \&amp; 和分隔符 #

      【讨论】:

        【解决方案3】:

        试试这个:

        < file_list.txt xargs -1 sed -i -e 'first_cmd' -e 'second_cmd' ...
        

        【讨论】:

          【解决方案4】:

          假设您有一个名为 file_list.txt 的文件,其中所有文件名都作为内容:

          file1.txt
          file2.txt
          file3.txt
          file4.txt
          

          您可以简单地将所有行读入一个变量(这里:files),然后遍历每一行:

          files=`cat file_list.txt`
          for file in $files; do
             echo "do something with $file"
          done
          

          【讨论】:

          【解决方案5】:

          使用awk 遍历入围文件名并使用xargs 执行sed。您可以使用-e 选项对一个文件执行多个sed 命令。

          awk '{print $1}' your_shortlisted_file_lists  | xargs sed -i -e first_sed -e second_sed $1
          

          xargs$1 变量中从awk 获取文件名。

          【讨论】:

          • 也许强调四个sed 脚本可以而且应该合并为一个脚本。
          • @tripleee,是的,这是一种更好的方法。此外,如果它归结为脚本,我们还可以使用 for loop 遍历文件并执行 sed's
          • @EdMorton,它将打印每行的第一个标记
          • 好的,这有什么用?您不认为 sed 脚本末尾的 $1 与 awk 命令中使用的 $1 相同吗?与cat your_shortlisted_file_lists 相比,我能说的最好的就是 awk 命令所做的唯一一件事就是在任何文件名包含空格时破坏脚本,但无论如何这都是 UUOC。
          猜你喜欢
          • 2017-07-09
          • 1970-01-01
          • 2016-05-20
          • 1970-01-01
          • 2014-11-03
          • 2012-08-31
          • 2022-08-10
          • 2012-11-02
          • 2018-10-30
          相关资源
          最近更新 更多