可以在命令行上 运行,但不能在 shell 脚本中?

Can be run on the command line, but not in a shell script?

我想用grep在文件中搜索匹配的字符串,但是由于文件太大,我只搜索前500行。

我在shell脚本中写道:

#!/bin/bash

patterns=(
llc_prefetcher_operat
to_prefetch
llc_prefetcher_cache_fill
)


search_file_path="mix1-bimodal-no-bop-lru-4core.txt"
echo ${#patterns[*]}
cmd="head -500 ${search_file_path} | grep -a "
for(( i=0;i<${#patterns[@]};i++)) do
cmd=$cmd" -e "\"${patterns[i]}\"
done;
echo $cmd
$cmd >junk.log

运行脚本的结果是:

3
head -500 mix1-bimodal-no-bop-lru-4core.txt | grep -a -e "llc_prefetcher_operat" -e "to_prefetch" -e "llc_prefetcher_cache_fill"
head: invalid option -a
Try'head --help' for more information.

在倒数第二行,我打印出了执行命令的字符串。我直接在命令行运行就成功了。 也就是下面这句话。

 head -500 mix1-bimodal-no-bop-lru-4core.txt | grep -a -e "llc_prefetcher_operat" -e "to_prefetch" -e "llc_prefetcher_cache_fill"

注意在grep命令中,如果我不加-a选项,会出现matching the binary file.

的问题

为什么会出现这个问题?谢谢!

与其尝试构建包含复杂命令的字符串,不如使用 grep-f 选项和 bash 进程替换来传递模式列表搜索:

head -500 "$search_file_path" | grep -Faf <(printf "%s\n" "${patterns[@]}") > junk.log

它更短、更简单且不易出错。

(我将 -F 添加到 grep 选项,因为 none 您的示例模式具有任何正则表达式元字符;因此固定字符串搜索可能会更快)


你所做的最大问题是当 $cmd 是单词拆分时,| 被视为 head 的另一个参数。它不像存在文字分隔符时那样被视为管道分隔符。