2016-01-21 68 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

相关问题