Score:0

Bash Script: Comparing two text files

by flag

I am wondering how I can do this efficiently. Given two files, say a.txt and b.txt, I want to write a bash script to do the following:

Every line in a.txt containing '*' that does not exist in b.txt will be added at the end of b.txt with a time stamp.

I can do the first and last parts by grep "*" a.txt echo "$(date)" >> b.txt but I don't know how about the rest.
pLumo avatar
in flag
Please edit your question and add some examples of your files and the expected output.
terdon avatar
cn flag
There is no way of being remotely efficient in bash. Does this _need_ to be bash? I see you are at least open to non-bash tools like `grep`, so can we also use `awk` or `sed` or `perl` etc? The shell, any shell, is a horrible tool for text processing: it will always be slow and inefficient.
Taro avatar
by flag
@terdon thank your for enlightening me.
Score:0
za flag

I suggest you to use a third file for results so you don't mess the b.txt file. You could try this:

cp b.txt c.txt 
for line in $(grep '*' a.txt); do
    # for each line found in a.txt
    echo "Found: $line"
    grep -q $line b.txt   # check its presence in b.txt
    if [ $? -ne 0 ]; then
        # if the result of the grep is not equal to 0
        # it means that the line has not been found in b.txt
        # then print the line in a third file with the leading timestamp
        echo "$(date): $line" >> c.txt
    fi
done

It's clear that maybe you should just improve the grep since I don't know hoe the row where you are searching the '*' is composed.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.