Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Comparing Contents of two files and Output result file

Status
Not open for further replies.

hello99hello

Programmer
Jul 29, 2004
50
CA
Hello All,

Could anyone help in writting a bash scripts to compare the contents of two files.

file1 (has this records)
2345
re890
23499

file2 (has this records)
2345
Re890
23500

I would like to compare the contents of the two files one line at time and output file3 which should have the following(That is difference in contents of file1 and file2):

re890 Re890
23499 23500

Thanx in advance for your help.
 
You normally use 'diff' to compare two files.
The benefit is, you can use 'patch' to work with the diff-output.

I don't know, how close to your needed output-format you can get with diff.

Other advantages of diff are: It can synchronize again, if whole lines are inserted or removed in one of the files.
comm is another std-compare-util.
If both don't fit your needs:
Code:
#!/bin/bash
#
#	compare two files.
#	ensure they have same length.
n=0
while read INPUT
	do
		a_line[$n]=$INPUT
		# echo "$n ${a_line[$n]}"
		let n=n+1
done < file1

n=0
while read INPUT
	do
		b_line[$n]=$INPUT
		# echo "$n ${b_line[$n]}"
		let n=n+1
done < file2

for (( i=0; i < n; ++i)) ;
do
	if [[ !  "x${a_line[$i]}" == "x${b_line[$i]}" ]] ; then
		echo "${a_line[$i]} ${b_line[$i]}"
	fi
done

seeking a job as java-programmer in Berlin:
 


Assuming that you are truly comparing these line for line and don't have to deal with having extra values in each file.

like...

file1 (has this records)
2345
re890
23499
23500

file2 (has this records)
2345
Re890
23500

line 4 matches line 3 and should be ignored.

you can use ...

paste file1 file2 | awk '{if ( $1 != $2 ) { print $0 }}'

 
Hey guys,
I was gonna post something like this but since someone already asked I'll just ask here. I need something similar to this but different. I want to distribute a file but I dont want the script to be modified, so I want the script to check itself line for line against the original on a webserver, how would I go about this?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top