Score:-6

How do I write a script that prints every line of a file that is not contained in a another file? (Bash script)

us flag

for example, I have 2 text files :

file1 consists of:

a 
b
bb
cc

file2 consists of:

aa
bc
ab

output should be:

$p1.sh file1 file2 
bb
cc

$p1.sh file2 file1
aa
bc
ab

how would I write this bash script? I was writing something like this but it was not working:

#!/bin/bash

cat "$1" | while read m  
do
    grep -f -v "$m" "$2"
done | sort -u

any sort of guidance would be appreciated! I am a beginner programmer and have no experience in writing scripts. Thank you!

hu flag
Does this answer your question? [How do I write a bash script that prints every line of one file also in second file](https://askubuntu.com/questions/1362883/how-do-i-write-a-bash-script-that-prints-every-line-of-one-file-also-in-second-f)
nl34 avatar
us flag
@mikewhatever Unfortunately no, that link looks at common lines, but here I am trying to print lines that are not common. The complete opposite task! :)
bac0n avatar
cn flag
`-f <file>` option takes a file as an argument. The file is actually a pattern list (one pattern per line). If you are trying to match literally, you should add `-F` too.
hu flag
It this homewotk? What does it have to do with Ubuntu?
NotTheDr01ds avatar
vn flag
I gave you a sympathy upvote, but I'm beginning to see why it's received so many downvotes. *You* asked the opposite question a few days ago, you haven't answered "why" you would need this either time (leading us to believe you want us to do your homework for you), and the second answer provided on your other question simply needs one flag to be changed to (hint) invert the answer, which you should be able to find if you had tried that answer and `man grep` to see the options. If it's not a homework question, it's an XY problem[https://meta.stackexchange.com/q/66377/902710].
Score:0
cn flag

I think you need to use the commands sort and comm for this job. For example:

comm -23 <(sort -u file1.txt) <(sort -u file2.txt) > file3.txt

I will leave it to you to play with the suppression flags (-1,-2,-3) for the desired outcome. I have used -23 as an example.

Another perhaps easier method is using awk as follows:

awk 'FNR==NR{lines[$0]=1;next} !($0 in lines)' file1 file2
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.