【发布时间】:2011-01-28 08:18:01
【问题描述】:
我正在尝试编写一个脚本来搜索目录中的文件和 greps 模式。类似于下面的除了,查找表达式要复杂得多(不包括特定的目录和文件)。
#!/bin/bash
if [ -d "${!#}" ]
then
path=${!#}
else
path="."
fi
find $path -print0 | xargs -0 grep "$@"
显然,上述方法不起作用,因为"$@" 仍然包含路径。我尝试了通过迭代所有参数以排除路径来构建参数列表的变体,例如
args=${@%$path}
find $path -print0 | xargs -0 grep "$path"
或
whitespace="[[:space:]]"
args=""
for i in "${@%$path}"
do
# handle the NULL case
if [ ! "$i" ]
then
continue
# quote any arguments containing white-space
elif [[ $i =~ $whitespace ]]
then
args="$args \"$i\""
else
args="$args $i"
fi
done
find $path -print0 | xargs -0 grep --color "$args"
但这些因引用输入而失败。例如,
# ./find.sh -i "some quoted string"
grep: quoted: No such file or directory
grep: string: No such file or directory
请注意,如果$@ 不包含路径,则第一个脚本会执行我想要的操作。
编辑:感谢您提供出色的解决方案!我结合了答案:
#!/bin/bash
path="."
end=$#
if [ -d "${!#}" ]
then
path="${!#}"
end=$((end - 1))
fi
find "$path" -print0 | xargs -0 grep "${@:1:$end}"
【问题讨论】: