Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I diff two sections of the same file?

I have a source file with two similar yet subtly different sections. I'd like to merge the two sections into one subroutine with a parameter that handles the subtle differences, but I need to be sure I'm aware of them all so I don't miss any.
What I usually do in such cases is copy each of the sections to a separate file and then use tkdiff or vimdiff to highlight the differences. Is there any way to skip the intermediate files and just diff two parts of the same file?

like image 782
Nathan Fellman Avatar asked Jan 12 '09 08:01

Nathan Fellman


People also ask

Which command gives all differences between two files?

diff stands for difference. This command is used to display the differences in the files by comparing the files line by line. Unlike its fellow members, cmp and comm, it tells us which lines in one file have is to be changed to make the two files identical.


2 Answers

i chose to rework @ordnungswidrig's answer into a bash function (i was only interested in the differences from a single file, but this could easily be changed to handle two different files...):

# find differences within a file giving start and end lines for both sections
function diff_sections {
  local fname=`basename $1`;
  local tempfile=`mktemp -t $fname`;
  head -$3 $1 | tail +$2 > $tempfile && head -$5 $1 | tail +$4 | diff -u $tempfile - ;
  rm $tempfile;
}

you call the function like so... diff_sections path/to/file 464 483 485 506

like image 83
stephen Avatar answered Sep 21 '22 20:09

stephen


The linediff plugin for Vim works well for me. Visually select one section of your file and type :Linediff. Visually select the other section and type :Linediff. It will put vim in to vimdiff mode, showing only the two sections you highlighted previously. Type:LinediffReset to exit vimdiff mode.

More info:

https://unix.stackexchange.com/a/52759/32477

https://superuser.com/a/414958/199800

like image 25
Christian Long Avatar answered Sep 22 '22 20:09

Christian Long