Question

I am trying to use substitution with regex patterns to replace all spaces in md5sum output with tabs, and flip the normal md5sum output (fingerprint<space>/path/to/file) so it prints the /path/to/file first, and the md5 fingerprint second in the output to STDOUT. I have it working pretty well, but for some reason not all my spaces are converting to tabs, as you can see with this sample output (see ps item on 4th item):

/bin/pidof  7b6aa27625786df26cd2511a6ccb8ec6 

/bin/ping   120d994f6bd6e05e10c7aa4ffeb157b9 

/bin/ping6  6578368ea1a280524ad5c944e8de825f 

/bin/ps a68ff229e6c54ffa71d3de956395af5c 

/bin/pwd    a30c8ea470134ba60d9008ca5723c556 

/bin/rbash  83f4aacf3157bfab413d009f48980e61 

Code

#!/usr/bin/perl -w

foreach $arg (@ARGV) {
push (@md5, `md5sum $arg`);
}

foreach $entry (@md5) {
$entry =~ s/(^.*) +(.*$)/$2\t$1/;
print $entry . "\n";
}

I created a sample directory with 4 blank text files named a,b,c and d, and ran my perl script, and it worked fine. What gives?

** GOOD OUTPUT IN TEST DIR *

host{user}114: ls
a  b  c  d  mymd5.pl
host{user}115: ./mymd5.pl *
a   d41d8cd98f00b204e9800998ecf8427e 

b   d41d8cd98f00b204e9800998ecf8427e 

c   d41d8cd98f00b204e9800998ecf8427e 

d   d41d8cd98f00b204e9800998ecf8427e 

mymd5.pl    719e2f8f878077ae3ef037369eb38e48 

host{user}116: 
Was it helpful?

Solution

What about this? It is using spaces to have a fixed length first column, then a TAB.

#!/usr/bin/perl -w
use strict;
use warnings;

my @md5;
my $longest_filename = 0;
foreach my $arg (@ARGV) {
   push (@md5, `md5sum $arg`);
   $longest_filename = length($arg) if length($arg)>$longest_filename;
}
chomp(@md5);


$longest_filename++;
foreach my $entry (@md5) {
  my ($md5,$filename) = $entry =~ m/^(.+?)\s(.+?)$/gis;
  printf "%-".$longest_filename."s\t%-16s\n",$filename,$md5;  
}


 bd.pl                                  b367dcf675902583a113a13e3b345809
 p1.pl                                  f5a10f748917ac8cf90d2e223c5b1cbf
 lognlonglong_filename_tohave.txt       d41d8cd98f00b204e9800998ecf8427e
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top