0

I am trying to write a shell script to simulate the following problem:

File A contains some entries like

a  
b  
c 

and File B contains

a  
g  
d  
t  
q  
c  

the final file should have
(contents of file b which are not there in file a)

g  
d  
t  
q  

I was trying something like this but it's not working:

for i in `cat b` ; do if[ (grep $i a) != $i ] then echo $i; done
1
  • Consider making a habit of running your code through shellcheck.net before asking questions here. Commented Mar 7, 2017 at 16:28

4 Answers 4

2

You code has some errors:

  1. forgot the closure of if statement : fi

  2. "grep $i a" must be interpreted as a command , such as $(grep $i a) or `grep $i a`

  3. You must add some characters around $(grep $i a) avoid empty string comparasion , such as ":" or something else, whatever.

Solution:

for i in `cat b` ; do if [ :$(grep $i a) != :$i ] ;then echo $i;fi; done
Sign up to request clarification or add additional context in comments.

Comments

2

Sort the files and then use comm. In bash:

comm -13 <(sort a) <(sort b)

This assumes you have a sufficiently recent bash (version 3.2 on Mac OS X 10.7.3 is not new enough; 4.1 is OK), and that your files are a and b. The <(sort a) is process substitution; it runs sort on a and the output is sent to comm as the first file; similarly for <(sort b). The comm -13 option suppresses the lines only in the first file (1, aka a) and in both files (3), thus leaving the lines only in 2 or b.

Your command:

for i in `cat b` ; do if[ (grep $i a) != $i ] then echo $i; done

shows a number of problems — four separate syntactic issues:

  1. Space before [
  2. Dollar before (
  3. Semicolon before echo
  4. fi; before done

Fixing them gives:

for i in `cat b`; do if [ $(grep $i a) != $i ]; then echo $i; fi; done

You could also use:

for i in `cat b`
do
    if grep $i a > /dev/null
    then : in both files
    else echo $i
    fi
done

1 Comment

Good answer, although it's not immediately obvious that you gave two separate answers.
1

Assuming A and B is your files, it can be done by diff

diff A B | grep '^>' | cut -d ' ' -f 2-

Comments

0
pearl.260> cat file3
i
a
b
c
pearl.261> cat file4
a
g
d
t
q
c
pearl.262> nawk 'FNR==NR{a[$1];next}!($1 in a)' file3 file4
g
d
t
q
pearl.263>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.