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

时间:2021-07-09 03:37:09

标签: shell grep

我想用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的问题。

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

1 个答案:

答案 0 :(得分:1)

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

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

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

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


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