伙计们,
我需要你的帮助,试图确定最快和最";故障;宽容地解决我的问题。我有一个shell脚本,它基于txt文件执行一些函数,其中有一个文件列表。该列表可以包含1个文件到X个文件。我想做的是迭代文件的内容,并只对文件中的4项执行脚本。执行完这4个文件的功能后,转到下一个4。。。。并继续这样做,直到列表中的所有文件都被"删除"为止;处理";。
到目前为止,我的代码如下。
#!/bin/bash
number_of_files_in_folder=$(cat list.txt | wc -l)
max_number_of_files_to_process=4
Translated_files=/home/german_translated_files/
while IFS= read -r files
do
while [[ $number_of_files_in_folder -gt 0 ]]; do
i=1
while [[ $i -le $max_number_of_files_to_process ]]; do
my_first_function "$files" & # I execute my translation function for each file, as it can only perform 1 file per execution
find /home/german_translator/ -name '*.logs' -exec mv {} $Translated_files ; # As there will be several files generated, I have them copied to another folder
sed -i "/$files/d" list.txt # We remove the processed file from within our list.txt file.
my_second_function # Without parameters as it will process all the files copied at step 2.
done
# here, I want to have all the files processed and don't stop after the first iteration
done
done < list.txt
不幸的是,由于我不太擅长shell脚本,我不知道如何构建它,这样它就不会浪费任何资源;过程";文件中的所有内容。你对如何实现我想要实现的目标有什么建议吗?
文件中只有4项。一旦对这4个文件执行了功能,转到下一个4
使用xargs似乎很容易。
your_function() {
echo "Do something with $1 $2 $3 $4"
}
export -f your_function
xargs -d 'n' -n 4 bash -c 'your_function "$@"' _ < list.txt
- 每条线路的
xargs -d 'n'
-n 4
接受参数bash ....
-使用4个参数运行此命令_
-语法为bash -c <script> $0 $1 $2 etc...
,请参见man bash
"$@"
-前向参数export -f your_function
-将您的函数导出到环境中,以便子bash可以获取它
我为每个文件执行翻译功能
因此,您对每个文件执行翻译函数,而不是对每4个文件执行翻译函数。如果";翻译功能";实际上,对于每个没有文件间状态的文件,考虑用相同的代码和xargs -P 4
并行执行4个进程。
如果你有GNU并行,它看起来像这样:
doit() {
my_first_function "$1"
my_first_function "$2"
my_first_function "$3"
my_first_function "$4"
my_second_function "$1" "$2" "$3" "$4"
}
export -f doit
cat list.txt | parallel -n4 doit