本文介绍了使用grep搜索多种模式的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想制作一个bash脚本,以使用grep搜索具有多个模式(不区分大小写)的行.我想创建一个bash脚本,可以按以下方式使用:
I want to make a bash script to use grep to search for lines which have multiple patterns (case-insensitive). I want to create a bash script which I can use as follows:
myscript file.txt pattern1 pattern2 pattern3
,它应该被翻译为:
grep -i --color=always pattern1 file.txt | grep -i pattern2 | grep -i pattern3
我尝试了以下bash脚本,但无法正常工作:
I tried following bash script, but it is not working:
#!/bin/bash
grep -i --color=always $2 $1 | grep -i $3 | grep -i $4 | grep -i $5 | grep -i $6 | grep -i $7
错误是:
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
推荐答案
我认为您可以执行递归功能:
I think you can do a recursive function:
search() {
if [ $# -gt 0 ]; then
local pat=$1
shift
grep "$pat" | search "$@"
else
cat
fi
}
在脚本中,您将调用此函数并将搜索模式作为参数传递.假设 $ 1
是文件,其余参数是模式,那么您就可以这样做
In your script you would call this function and pass the search patterns as arguments. Say that $1
is the file and the rest of the arguments are patterns then you would do
file=$1
shift
cat "$file" | search "$@"
这篇关于使用grep搜索多种模式的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!