My question is how to compare two lines in two separate files? Basically I have two files, file1 contains a line:


file2 contains a line:


What I have tried is:

diff -u file1 file2 > file3

but that does not give aaaa as it should. Also both files are not always the same, but the difference is always at the begin of the line.

I have modified my program so that I now have two vars one with aaaabaaabaabab and one with a. Now I can do the following:

echo ${var1##*$var2} > tempfile.txt

tempfile contains baaabaabab. But how do I get aaaa? I was thinking of:

echo ${var1//*$var2} > tempfile.txt

but that does not work.

  • Does each file only have one line? It sounds like you need to compare one line, character-by-character. Is that right? Nov 2 '15 at 17:29
  • yes each file only has one line. But because the difference only occurs at the beginning of the line isn't it plausible to do some sort of substraction
    – bob
    Nov 2 '15 at 17:32
  • diff operates on a line comparison basis, it won't print substrings of lines that differ. I'm not sure there is a prepackaged utility to do what you want, I think you'll have to write your own.
    – John
    Nov 2 '15 at 17:36

diff works on a per-line basis. So if lines differ even just by one character, then diff considers them to be different.

One thing you could do in your case is transform your input data such that each character is on its own line. The fold command helps with this. So you could do something like:

$ diff <(fold -w1 file1) <(fold -w1 file2)
< a
< a
< a
< a

This only works if your input files really do only have one line each.

I don't know whether or not this output format is useful to you. If you literally want the "aaaa" string, and you are absolutely guaranteed that the difference is only at one place in the input lines, then you could pipe the above output through awk:

$ diff <(fold -w1 file1) <(fold -w1 file2) | awk '/^< / { printf $2 }'

Here's a way using perl to remove the contents from the second file from the contents of the first, then print the remaining from the first file to an output file:

perl -e '$x=<>; $y=<>; $x=~s/$y//; print $x' 1.txt 2.txt > out.txt
  • you probably want to $y=quotemeta $y; in case there are regexp-special characters.
    – cas
    Nov 2 '15 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.