簡體   English   中英

Linux命令替換目錄下一組文件的行集

[英]Linux command to replace set of lines for a group of files under a directory

我只需要替換選定的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天以上的時間。

有什么辦法嗎?

使用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獲取文件名。

嘗試這個:

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

沒有回答您的問題,而是提出改進建議。 四個用於替換標頭的sed命令效率很低。 我將把新的標頭寫入文件中並執行以下操作

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

將用標頭替換文件的前四行。

當前s###方法的另一個問題是,您必須注意要替換的文本中的特殊字符\\&和分隔符#

您可以將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

假設您有一個名為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM