如何在 bash 中从 list.txt 创建多个文件名并更改新创建文件的文本?

如何在 bash 中从 list.txt 创建多个文件名并更改新创建文件的文本?

我想使用文件 list.txt 中的名称以及每个文件中的文本一次创建多个文件。假设我有一个list.txt包含一些id.数字,现在我想使用该 ids 作为名称(例如,,l)来制作单独的EOG090W002U_M0.ctl文件。此外,文件的内容也需要相应更改。EOG090W00C1_M0.ctlEOG090W00DC_M0.ct

样本list.txt:

EOG090W002U 
EOG090W00C1 
EOG090W00DC 
EOG090W00DE 
EOG090W00E5
EOG090W00HR 
EOG090W00MH 
EOG090W00MS 
EOG090W00PB 
EOG090W00U4
EOG090W00UK 
EOG090W00WM 
EOG090W00WR

例如EOG090W002U_M0.ctlEOG090W00C1_M0.ctl文件的所需内容将是

seqfile = EOG090W002U_p.phy
treefile = Sametree.txt
outfile = EOG090W002U_M0_mlc

getSE = 0
RateAncestor = 1
Small_Diff = 5e-7
cleandata = 1
fix_blength = 2
method = 0

或者

seqfile = EOG090W00C1_p.phy
treefile = Sametree.txt
outfile = EOG090W00C1_M0_mlc

  getSE = 0
  RateAncestor = 1
  Small_Diff = 5e-7
  cleandata = 1
  fix_blength = 2
  method = 0

这里,seqfileoutfile将根据 进行更改,list.txt但文件中的其他文本将保持不变。

谢谢

答案1

您可以while在此处文档周围使用循环:

while IFS= read -r x; do
  cat << EOF > "${x}_M0.ctl"
  seqfile = ${x}_p.phy
  treefile = Sametree.txt
  outfile = ${x}_M0_mlc

    getSE = 0
    RateAncestor = 1
    Small_Diff = 5e-7
    cleandata = 1
    fix_blength = 2
    method = 0
EOF
done < list.txt

如果您的行中list.txt有前导或尾随 SPC 或 TAB 字符,则应不是被解释为文件名的一部分(并且您没有以其他方式修改该IFS变量),然后省略命令IFS=之前的赋值read

while read -r x; do

或者明确将其设置为 SPC 和 TAB:

while IFS=$' \t' read -r x; do

(请注意,将其扩展为其他空白字符(如CR, FF, NBSP... )将不起作用,因为它们没有接受特殊的 IFS 空白处理,只有 SPC、TAB 和 NL 接受特殊的 IFS 空白处理。

答案2

#!/bin/bash
tr -d '[:blank:]' < list.txt > outputFile.tmp

for i in $(cat outputFile.tmp)
do
  echo "seqfile = ${i}_p.phy" >> ${i}_M0.ctl
  echo "treefile = Sametree.txt" >> ${i}_M0.ctl
  echo "outfile = ${i}_M0_mlc" >> ${i}_M0.ctl
  echo "" >> ${i}_M0.ctl
  echo "getSE = 0" >> ${i}_M0.ctl
  echo "RateAncestor = 1" >> ${i}_M0.ctl
  echo "Small_Diff = 5e-7" >> ${i}_M0.ctl
  echo "cleandata = 1" >> ${i}_M0.ctl
  echo "fix_blength = 2" >> ${i}_M0.ctl
  echo "method = 0" >> ${i}_M0.ctl
done
exit 0

相关内容