通过shell脚本唯一地命名文件

时间:2014-02-24 01:06:48

标签: bash shell

我正在尝试创建一个遍历指定目录的bash脚本,查找文件,对其内容进行排序,然后创建一个新文件。我现在遇到的唯一问题是如何为每个文件指定一个不同的名称。代码:

find $1 -name '*.grd' -exec sort -k 2,2 {}> {}.std \;

1 个答案:

答案 0 :(得分:3)

find命令中进行重定向时,shell在启动find之前只执行一次重定向。由于-exec直接使用execv()调用来调用子进程 - 没有shell - 其参数内的重定向将不受尊重。 (>file等重定向由调用shell执行,而不是作为执行过程的一部分由操作系统执行。

对于大多数控件,不要尝试使用find -exec,而是直接在shell中处理结果:

while IFS= read -r -d '' filename; do
  sort -k2,2 <"$filename" >"${filename}.std"
done < <(find "$1" -name '*.grd' -print0)

或者,如果您坚持使用find -exec,请让它自己启动一个shell,并在那里进行处理和重定向:

find "$1" -name '*.grd' -exec bash -c \
  'while (( $# )); do sort -k2,2 <"$1" >"$1.std"; shift; done' _ {} +

the UsingFind page on the Wooledge wiki提供了其他方法(特别参见第5至8节)。