merging files in linux
Hi all,
Assume that i am having two files file1 and file2. these were the contents of file1 Name=Dinesh Age=24 sex=male character=good profession=admin these were the contents of file2 Name=vino Age=22 sex=female Now i want to copy only the contents from file1 which were not in file2. i.e. after copying my file2 content should look like this. Name=vino Age=22 sex=female character=good profession=admin i.e. only the content which is not in file2 needs to be copied, remaining content should be undisturbed. In linux is there a way to do this. If possible kindly post your suggestions. Thanks in advance, Dinesh. |
A quick 'n dirty method:
Code:
diff -y file[12] | sed '/< $/!s/=[^=]*=/=/g' |
Note that the solution proposed by Ignotum per Ignoius assumes that your two files were literally named "file1" and "file2." If your actual names are different from those, the diff command should be written with the two file names following the -y option.
You can look at the output of man diff for a description of the diff command. (And, of course, man sed for a description of the stream editor into which the diff output is piped.) |
Quote:
|
Hi Ignotum,
I used your code,this is the output. root@dinesh-laptop:~# diff -y file1 file2 | sed '/< $/!s/=[^=]*=/=/g' Name=vino Age=22 sex=female character=good < profession=admin < But the contents is not copied to file2. it remains the same. |
Quote:
Filter out the extraneous angle brackets with another application of sed. Quote:
Here's a one-liner that should do what you want: Code:
diff -y file[12] | sed '/<$/!s/=[^=]*=/=/g' | sed 's/<$//g' > .tmpfile2 && mv .tmpfile2 file2 |
Hi,
Thank you that works fine. But i have one doubt is it necessary to redirect the output to a hidden file. if thats the case can you please explain me why we cant redirect to a regular file. |
Quote:
Quote:
Quote:
|
Alternative:
Code:
awk -F"=" 'NR == FNR{_[$1]=$0;next}!($1 in _){print _[$1]}' file1 file2 > file3; mv file3 file2 |
Hi grail,
Thanks for your reply, i executed your code without redirecting to a file.and this is the output i got. [root@localhost ~]# awk -F"=" 'NR == FNR{_[$1]=$0;next}!($1 in _){print _[$1]}' file1 file2 [root@localhost ~]# Actually it looks empty. Your suggestions please. |
You can also try kdiff3, it is more user friendly! If you are using Kde, it will be
installed by default. |
Sorry about that ... appears I was on drugs with my thinking :(
This seems to do what you want: Code:
awk -F"=" 'NR == FNR{_[$1]=$0;next}$1 in _{delete _[$1];print}END{for(x in _)print _[x]}' file1 file2 |
Another alternative using the diffs and sed earlier, I am just not sure if appending straight away might cause issues:
Code:
diff -y file[12] | sed -n '/</s/ .*$//p' >> file2 I am sure some guru will let us know :) |
Hi,
Thanks that works.Thanks to all especially to Ignotum. |
...Happy to have helped. :)
All the best. |
All times are GMT -5. The time now is 10:57 PM. |