【问题标题】:Linux bash scripting for 2 folders at the same time同时为 2 个文件夹编写 Linux bash 脚本
【发布时间】:2016-02-11 23:16:45
【问题描述】:

这是我的 bash 可执行命令:

while read line
do
./ngram -order 1 -lm path1/$line -ppl path2/$line -debug 4 > path3/$line
done < input_list_of_files

所以,我有两个文件夹,一个在 path1 中,另一个在 path2 中。路径 1 和路径 2 具有相同的文件名,但具有不同的扩展名。例如, Path1 有许多扩展名为“.txt”的文件(file1.txt),而 path2 有许多扩展名为“.title”的文件(file1.title)。

也就是说,路径1有文件夹folder1,里面有文件file1.txt、file2.txt、file3.txt等等。同样,路径2有文件夹folder2,里面有file1.title、file2.title、file3等文件.title 等等..

list_of_files 有数据:

file1.txt
file2.txt
file3.txt

等等……

我想在“-lm”选项后输入file1.txt,在“-ppl”选项后输入file1.title。当我一次操作一个文件时,这很好用。

也就是说,当在“-lm”之后输入file1.txt,那么同时,我们应该在“-ppl”之后有file1.title。

我想通过同时输入相同的文件名但不同的扩展名来同时对文件夹中的所有文件进行批处理计算。我该怎么做?请帮忙!

我用过的例子:

./ngram -order 1 -lm Path1/Army_recruitment.txt -ppl Path2/Army_recruitment.title -debug 4 > Path3/Army_recruitment.txt

输出文件如下:

 military troop deployment number need
p( military | <s> )     = [1gram] 0.00426373 [ -2.37021 ]
p( troop | military ...)    = [1gram] 0.00476793 [ -2.32167 ]
p( deployment | troop ...)  = [1gram] 0.00045413 [ -3.34282 ]
p( number | deployment ...)     = [1gram] 0.0015224 [ -2.81747 ]
p( need | number ...)   = [1gram] 0.000778574 [ -3.1087 ]
p( </s> | need ...)     = [OOV] 0 [ -inf ]
1 sentences, 5 words, 0 OOVs
1 zeroprobs, logprob= -13.9609 ppl= 619.689 ppl1= 3091.84 
5 words, rank1= 0 rank5= 0 rank10= 0
6 words+sents, rank1wSent= 0 rank5wSent= 0 rank10wSent= 0 qloss=    0.998037 absloss= 0.998036

file Army_recruitment_title.txt: 1 sentences, 5 words, 0 OOVs
1 zeroprobs, logprob= -13.9609 ppl= 619.689 ppl1= 3091.84
5 words, rank1= 0 rank5= 0 rank10= 0
6 words+sents, rank1wSent= 0 rank5wSent= 0 rank10wSent= 0 qloss=   0.998037 absloss= 0.998036 

此输出是根据可执行文件 ./ngram 生成的。这是来自一个包。

【问题讨论】:

  • 您能否通过提供input_list_of_files 的示例内容以及path1path2 目录的目录列表来澄清这个问题?
  • 我已经编辑过了。请看一看。
  • 对不起,请立即检查...现在编辑清楚
  • 这个问题仍然没有预期的输出。
  • pluse-uno 用于改进您的问题。祝大家好运。

标签: linux bash


【解决方案1】:
# As suggested by @CharlesDuffy: use read -r to ensure that text is taken literally
while read -r line ; do
    name="${line%.txt}"     # Strip off .txt extension
    ./ngram -order 1 -lm "path1/$name.txt" -ppl "path2/$name.title" -debug 4 > "path3/$name"
done < input_list_of_files

【讨论】:

    【解决方案2】:

    您可以使用命令basename 去除目录名称之外的路径后缀。所以:

    while read line
    do
    path2file=$(basename $line .txt).title
    ./ngram -order 1 -lm path1/$line -ppl path2/$path2file -debug 4 > path3/$line
    done < input_list_of_files
    

    (假设您仍然希望在输出文件末尾添加.txt

    【讨论】:

    • 与参数扩展方法相比,这效率非常低
    • 改为考虑path2file=${line%.txt}.title -- 没有用于子shell 的fork,没有执行外部工具。
    • ...此外,您在这里缺少大量引号,因此此代码对于带有空格的文件名会表现得很糟糕(通过shellcheck.net 运行它以指出那些),并且因为它不使用 read-r 参数,它也会在包含文字反斜杠的文件名中出现错误。
    猜你喜欢
    • 1970-01-01
    • 2012-12-09
    • 2018-07-12
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2013-09-29
    • 1970-01-01
    相关资源
    最近更新 更多