2016-01-21 59 views
1

我有很多擴展名爲.com的文件,所以這些文件被命名爲001.com002.com003.com,等等。使用bash添加一個文本到多個文件

而且我有一個名爲headname另一個文件,其中包含以下信息:

abc=chd 
dha=djj 
cjas=FILENAME.chk 
dhdh=hsd 

我需要把文件HEADNAME的內部信息(並在開始的)文件001.com002.com003.com和等等......但FILENAME需要是將接收headname信息(沒有.com擴展名)的文件的文件名。

所以輸出必須是:

對於001.com

abc=chd 
dha=djj 
cjas=001.chk 
dhdh=hsd 

對於002.com

abc=chd 
dha=djj 
cjas=002.chk 
dhdh=hsd 

對於003.com

abc=chd 
dha=djj 
cjas=003.chk 
dhdh=hsd 

等等...

+0

像'在 F; do sed「s/FILENAME/$ f/g'headname>」$ {f} .com「; done'? – Biffen

回答

1

像這樣的東西應該工作:

head=$(<headname)  # read head file into variable 
head=${head//$'\n'/\\n} # replace literal newlines with "\n" for sed 
for f in *.com; do  # loop over all *.com files 
    # make a backup copy of the file (named 001.com.bak etc). 
    # insert the contents of $head with FILENAME replaced by the 
    # part of the filename before ".com" at the beginning of the file  
    sed -i.bak "1i${head/FILENAME/${f%.com}}" "$f" 
done 
+0

太棒了!!!這工作完美! – alloppp

4
set -e 

for f in *.com 
do 
    cat <(sed "s#^cjas=FILENAME.chk\$#cjas=${f%.com}.chk#" headname) "$f" > "$f.new" 
    mv -f "$f.new" "$f" 
done 

說明:

  • for f in *.com - 這遍歷與.com結尾的所有文件名。
  • sed是一個可以用來代替文本的程序。
  • s#...#...#是替代命令。
  • ${f%.com}是沒有.com後綴的文件名。
  • cat <(...) "$f" - 這將新頭與.com文件的主體合併。
  • cat的輸出存儲在名爲123.com.new的文件中 - mv -f "$f.new" "$f"用於將123.com.new重命名爲123.com
+0

過程替換在這裏是不必要的複雜化;'sed ... | cat - 」$ f「>」$ f.new「' – chepner

相關問題