我有一个文件夹存档数百个文本文件,我想运行一个名为mint
的Linux命令。此命令输出一个文本值,我想要将其存储在唯一文件中,对于文件夹中的每个文件都有一个值。有没有办法使用*
字符来运行该命令来表示所有的输入文件,同时仍然将输出管道输送到独立于每个其他文件的文件?Linux:管道输出到唯一文件
例子: $ mint * > uniqueFile.krn
我有一个文件夹存档数百个文本文件,我想运行一个名为mint
的Linux命令。此命令输出一个文本值,我想要将其存储在唯一文件中,对于文件夹中的每个文件都有一个值。有没有办法使用*
字符来运行该命令来表示所有的输入文件,同时仍然将输出管道输送到独立于每个其他文件的文件?Linux:管道输出到唯一文件
例子: $ mint * > uniqueFile.krn
随着修复的错误和警告关闭:
#!/bin/bash
# ^^^^ - bash, not sh, for [[ ]] support
for f in *.krn; do
[[ $f = *.krn ]] && continue # skip files already ending in .krn
mint "$f" >"$f.krn"
done
或者,用一个前缀:
您也能避免重建已经存在的,除非哈希源文件已更改:
for f in *; do
# don't hash hash files
[[ $f = int_* ]] && continue
# if a non-empty hash file exists, and is newer than our source file, don't hash again
[[ -s "int_$f" && "int_$f" -nt "$f" ]] && continue
# ...if we got through the above conditions, then go ahead with creating a hash
mint "$f" >"int_$f"
done
为了解释:
test -s filename
是真实的,只有如果给定名称的文件存在且非空test file1 -nt file2
是真的只有存在这两个文件,并file1
较新,file2
。[[ ]]
不同于导出了test
命令KSH-扩展shell语法,对于模式匹配测试添加支持(即仅当$string
膨胀以在.txt
结束的值[[ $string = *.txt ]]
将为真),和放松的引用规则(编写[[ -s $f ]]
是安全的,但test -s "$f"
需要引号来处理所有可能的文件名)。感谢您的所有建议! Shiping的解决方案效果很好,我只在文件名后加了一个前缀。像这样:
$ for file in * ; do mint $file > int_$file ; done
自答从问题和标记的社区Wiki中移出;请参阅What is the appropriate action when the answer to a question is added to the question itself?
这有一些错误。例如,如果您多次运行它,它将创建名称为“int_int_foo”文件的文件,并且它不会正确处理其名称中包含空格的文件。 –
您可以尝试“for file in *; do mint $ file> $ file.krn; done” – Shiping
但是,如果您有例如'file1'和'file1.krn'作为输入文件,您将得到不需要的覆盖。你似乎可能证实没有'.krn'文件,但为了安全起见,如果使用bash,你可以设置noclobber:'set -C'。 –
复制并尝试'parallel'mint {}> {} .krn'::: *' –