bash text search: find if the content of one file

2020-02-14 05:42发布

Say we have two files: a.txt and b.txt. Each file has multiple lines of text.

How do I write a shell script to check if all of the content of a.txt exists in b.txt?


Thx for the hints guys, i didn't noticed -q will output 0 if successfully matched.

I end up with:

if grep a.txt -q -f b.txt ; then

else

fi

标签: bash shell
4条回答
何必那么认真
2楼-- · 2020-02-14 06:01

try grep

cat b.txt|grep -f a.txt
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-14 06:05

Here is a script that will do what what you are describing:

run: sh SCRIPT.sh a.txt b.txt

# USAGE:   sh SCRIPT.sh TEST_FILE CHECK_FILE
TEST_FILE=$1
CHECK_FILE=$2

## for each line in TEST_FILE
while read line ; do

    ## check if line exist in CHECK_FILE; then assign result to variable
    X=$(grep "^${line}$" ${CHECK_FILE})


    ## if variable is blank (meaning TEST_FILE line not found in CHECK_FILE)
    ## print 'false' and exit
    if [[ -z $X ]] ; then
        echo "false"
        exit
    fi

done < ${TEST_FILE}

## if script does not exit after going through each line in TEST_FILE,
## then script will print true
echo "true"

Assumptions:

  • line order from a.txt does not matter
查看更多
叛逆
4楼-- · 2020-02-14 06:06

Using grep

grep -f a.txt b.txt
查看更多
祖国的老花朵
5楼-- · 2020-02-14 06:12

You need to write a loop that iterates over each line in a.txt and use grep (or some other means) to see if that line is in b.txt. If you find any instance where it is not in b.txt, then you can provide the answer: not all lines match. If you find no such instances, you can conclude that all lines match.

Capturing the output of grep using backticks would likely be useful:

if [`grep -v $line b.txt`==  ""]; then

kind of thing.

If you have specific questions about how to iterate over the contents of a file, you should ask a specific question about that, showing what you tried.

查看更多
登录 后发表回答