![如何在 bash 中从 list.txt 创建多个文件名?](https://linux22.com/image/166316/%E5%A6%82%E4%BD%95%E5%9C%A8%20bash%20%E4%B8%AD%E4%BB%8E%20list.txt%20%E5%88%9B%E5%BB%BA%E5%A4%9A%E4%B8%AA%E6%96%87%E4%BB%B6%E5%90%8D%EF%BC%9F.png)
我想使用一个文件中的名称一次创建多个文件list.txt
,我该怎么做?
样本list.txt
:
EOG090W002U
EOG090W00C1
EOG090W00DC
EOG090W00DE
EOG090W00E5
EOG090W00HR
EOG090W00MH
EOG090W00MS
EOG090W00PB
EOG090W00U4
EOG090W00UK
EOG090W00WM
EOG090W00WR
假设我有这个list.txt
包含一些 ID 号。现在我想使用这些 id 作为名称来创建单独的文件(例如,,,EOG090W002U_M0.ctl
)。此外,文件的内容也需要相应更改。例如,文件的内容将是EOG090W00C1_M0.ctl
EOG090W00DC_M0.ctl
EOG090W002U_M0.ctl
EOG090W00C1_M0.ctl
seqfile = EOG090W002U_p.phy
treefile = Constant.txt
outfile = EOG090W002U_M0_mlc
或者
seqfile = EOG090W00C1_p.phy
treefile = Constant.txt
outfile = EOG090W00C1_M0_mlc
其中*.phy
和Constant.txt
将在同一文件夹中提供。
答案1
最简单:
xargs touch <List.txt
神奇之处在于xargs
它获取标准输入中的每一行并将其作为参数添加到命令中。
答案2
在脚本中使用 GNU 并行:
#!/bin/bash
constant=constant
populate_file () {
local const=$1
local file=$(basename -s '.M0.ctl' "$2")
printf '%s\n%s\n%s\n' \
"seqfile = ${file}_p.phy" \
"treefile = ${const}.txt" \
"outfile = ${file}_M0_mlc" > "$2"
}
export -f populate_file
parallel populate_file "$constant" {}.M0.ctl :::: list.txt
这将从每一行中并行读取行list.txt
并执行该函数。populate_file
该populate_file
函数将以所需的格式将三行输出到每个文件中。
在没有 GNU 并行的情况下,您可以使用 while 读取循环:
#!/bin/bash
constant=constant
populate_file () {
local const=$1
local file=$(basename -s '.M0.ctl' "$2")
printf '%s\n%s\n%s\n' \
"seqfile = ${file}_p.phy" \
"treefile = ${const}.txt" \
"outfile = ${file}_M0_mlc" > "$2"
}
while IFS= read -r file; do
populate_file "$constant" "${file/ /}.M0.ctl"
done < list.txt
答案3
你可以尝试这样的事情:
for i in $(cat list.txt); do touch $i; done
答案4
#!/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 = constant.txt" >> ${i}_M0.ctl
echo "outfile = ${i}_M0_mlc" >> ${i}_M0.ctl
done
exit 0
解释:
tr -d '[:blank:]' < list.txt > outputFile.tmp
将从列表中删除空白并将其复制到outputFile.tmp
for
循环读取文件中的所有行outputFile.tmp
,并通过动态创建文件来将必要的上下文添加到文件中。