0

I need some assistance on the below.

File1.txt

aaa:/path/to/aaa:777
bob:/path/to/bbb:700
ccc:/path/to/ccc:600

File2.txt

aaa:/path/to/aaa:700
bbb:/path/to/bbb:700
ccc:/path/to/ccc:644

I should iterate file2.txt and if aaa exists in File1.txt, then i should compare the file permission. If the file permission is same for aaa in both the files then ignore.

If they are different then write them in the output.txt

So in above case

Output.txt

aaa:/path/to/aaa:700
ccc:/path/to/ccc:644

How can i achieve this in unix shell script? Please suggest

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 1
    1) write code 2) execute code 3) debug code. You are entirely responsible for #1-2, we (maybe) help with #3. – Marc B Jul 28 '16 at 21:49

2 Answers2

1

I agree with the comment of @Marc that you should try something before asking here.
However, the following answer is difficult to find when you never have seen the constructions, so I give you something to study.

When you want to parse line by line, you can start with

while IFS=: read -r file path mode; do
   comparewith=$(grep "^${file}:${path}:" File2.txt | cut -d: -f3)
   # compare and output
done < File1.txt

For large files that will become very slow. You can first filter the lines you want to compare from File2.txt. You want to grep strings like aaa:/path/to/aaa:, including the last :. With cut -d: -f1-2 you might be fine with your inputfile, but maybe it is better to remove the last three characters: sed 's/...$//' File1.txt.
You can let grep use the output as a file with expressions using <():

grep -f <(sed 's/...$//' File1.txt) File2.txt

Your example files don't show the situation when both files have identical lines (that you want to skip), you will need another process substitution to get that working:

grep -v -f File1.txt <(grep -f <(sed 's/...$//' File1.txt ) File2.txt )

Another solution, worth trying yourself, is using awk (see What is "NR==FNR" in awk? for accessing 2 files).

Community
  • 1
  • 1
Walter A
  • 19,067
  • 2
  • 23
  • 43
0

comm - compare two sorted files line by line

According to manual, comm -13 <file1> <file2> must print only lines unique to <file2>:

$ ls
File1.txt  File2.txt
$ cat File1.txt 
aaa:/path/to/aaa:777
bbb:/path/to/bbb:700
ccc:/path/to/ccc:600
$ cat File2.txt 
aaa:/path/to/aaa:700
bbb:/path/to/bbb:700
ccc:/path/to/ccc:644
$ comm -13 File1.txt File2.txt 
aaa:/path/to/aaa:700
ccc:/path/to/ccc:644
$ # Nice!

But it doesn't check for lines in <file1> that are "similar" to corresponding lines of <file2>. I. e. it won't work as you want if File1.txt has line BOB:/path/to/BOB:700 and File2.txt has BBB:/path/to/BBB:700 since it will print the latter (while you want it not to be printed).

It also won't do what you want if strings bbb:/path/to/bbb:700 and bbb:/another/path/to/bbb:700 are supposed to be "identical".

belkka
  • 264
  • 2
  • 13