我试图使用grep来匹配包含两个不同字符串的行。我已经尝试了以下方法,但这匹配了包含不是我想要的string1或string2的行。

grep 'string1\|string2' filename

那么我如何匹配与grep只包含两个字符串的行?


当前回答

grep -i -w 'string1\|string2' filename

这适用于精确的单词匹配和匹配不区分大小写的单词,为此使用-i

其他回答

你可以尝试这样做:

(pattern1.*pattern2|pattern2.*pattern1)

我经常遇到和你一样的问题,我刚刚写了一段脚本:

function m() { # m means 'multi pattern grep'

    function _usage() {
    echo "usage: COMMAND [-inH] -p<pattern1> -p<pattern2> <filename>"
    echo "-i : ignore case"
    echo "-n : show line number"
    echo "-H : show filename"
    echo "-h : show header"
    echo "-p : specify pattern"
    }

    declare -a patterns
    # it is important to declare OPTIND as local
    local ignorecase_flag  filename linum header_flag colon result OPTIND

    while getopts "iHhnp:" opt; do
    case $opt in
        i)
        ignorecase_flag=true ;;
        H)
        filename="FILENAME," ;;
        n)
        linum="NR," ;;
        p)
        patterns+=( "$OPTARG" ) ;;
        h)
        header_flag=true ;;
        \?)
        _usage
        return ;;
    esac
    done

    if [[ -n $filename || -n $linum ]]; then
    colon="\":\","
    fi

    shift $(( $OPTIND - 1 ))

    if [[ $ignorecase_flag == true ]]; then
    for s in "${patterns[@]}"; do
            result+=" && s~/${s,,}/"
    done
    result=${result# && }
    result="{s=tolower(\$0)} $result"
    else
    for s in "${patterns[@]}"; do
            result="$result && /$s/"
    done
    result=${result# && }
    fi

    result+=" { print "$filename$linum$colon"\$0 }"

    if [[ ! -t 0 ]]; then       # pipe case
    cat - | awk "${result}"
    else
    for f in "$@"; do
        [[ $header_flag == true ]] && echo "########## $f ##########"
        awk "${result}" $f
    done
    fi
}

用法:

echo "a b c" | m -p A 
echo "a b c" | m -i -p A # a b c

你可以把它放在。bashrc中。

你应该有这样的grep:

$ grep 'string1' file | grep 'string2'
grep ‘string1\|string2’ FILENAME 

GNU grep 3.1版

发现仅以6个空格开始并以以下内容结束的行:

 cat my_file.txt | grep
 -e '^      .*(\.c$|\.cpp$|\.h$|\.log$|\.out$)' # .c or .cpp or .h or .log or .out
 -e '^      .*[0-9]\{5,9\}$' # numers between 5 and 9 digist
 > nolog.txt