Consider the need to use 'diff' to compare two files with many commented lines, such as system configuration files. (For example, the files could be /etc/cups/cups-files.conf.pacnew and /etc/cups/cups-files.conf.)

I would like to ignore differences of any lines that are commented out such as these:

< #DocumentRoot /usr/share/cups/doc
> #DocumentRoot /usr/share/cups/doc-root

I only want to see differences of active (uncommented) lines.

(I would also like to ignore whitespace differences. I mention that for completeness in case the solution for the above interferes with using the the -w option.)

  • Other than -I? – Ignacio Vazquez-Abrams Feb 17 '18 at 21:59
  • @Ignacio -I only works if you have no mixed hunks – e.g. if you use -I '^#', but add one commented line followed by a non-commented line, you’ll see both in the diff output because they’re part of the same hunk. – Stephen Kitt Feb 17 '18 at 22:07

You can filter the commented lines before comparing the files:

diff -u -w <(grep -v '^[[:space:]]*#' /etc/cups/cups-files.conf.pacnew) <(grep -v '^[[:space:]]*#' /etc/cups/cups-files.conf)

That way diff will only see uncommented lines, and will only compare those.

  • can this be easily modified to work when the comment symbol is not in column 0? (That would be true in the case of leading whitespace.) – MountainX Feb 17 '18 at 22:10
  • This does not account for lines that may have comments at the end of them. A line that contains DocumentRoot /usr/share/cups/doc #some comment here would be excluded, regardless of whether the "active" part is different between files. – Hiko Haieto Feb 17 '18 at 22:11
  • @MountainX see the update. – Stephen Kitt Feb 17 '18 at 22:12
  • @Hiko no, it only excludes lines consisting solely of a comment. – Stephen Kitt Feb 17 '18 at 22:12
  • @HikoHaieto: Default config files are almost never commented in that manner. – Ignacio Vazquez-Abrams Feb 17 '18 at 22:12

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.