ferozalam_82 ferozalam_82 - 4 months ago 22
Linux Question

How to use `diff` on files whose paths contain whitespace

I am trying to find the differences between files, but the filename and directory name contain white space. I am trying to execute the command in a Perl script.

diff /home/users/feroz/logs/back_up20161112/Security File/General Security.csv /home/users/feroz/logs/back_up20161113/Security File/General Security.csv


open( my $FH, '>', $logfile ) or die "Cannot open the file '$logfile' $!";

foreach $filename ( keys %filenames ) {

$old_file = $parent_directory . $previous_date . $search_directory . "$filenames{$filename}";
$new_file = $parent_directory . $current_date . $search_directory . "$filenames{$filename}";

if ( !-e $old_file ) {

#print ("\nFile does not exist in previos date backup");

print $FH "\nERROR:'$old_file' ---- does not exist in the backup directory ";
elsif ( !-e $new_file ) {

#print ("\n The file does not exist in current directory");

print $FH "\nERROR:'$new_file' --- does not exist in the present directory ";
else {

# print $FH "\nDifference between the files $filenames{$filename} of $previous_date and $current_date ";

my $cmd = 'diff $old_file $new_file| xargs -0';
open( my $OH, '|-', $cmd ) or die "Failed to read the output";
while ( <OH> ) {
print $FH "$_";
close $OH;


Thank you for showing your Perl code

Single quotes don't interpolate, so that will pass the strings $old_file and $new_file to the command instead of those variables' contents. The shell will then try to interpret them as shell variables

I suggest that you write this instead

my $cmd = qq{diff '$old_file' '$new_file' | xargs -0};
open( my $OH, '|-', $cmd ) or die "Failed to read the output";

That will use double quotes (qq{...}) around the command string so that the variables are interpolated. The file paths have single quotes around them to indicate that the shell should treat them as individual strings

This won't work if there's a chance that your file paths could contain a single quote, but that's highly unusual