summaryrefslogtreecommitdiffstats
path: root/reformat_fstab.pl
blob: 9c81d8d53b96c0221afd3cd35b859c9b3a06ccb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#! /usr/bin/perl
use warnings;
use strict;

my $fstabFile = shift;
my $fstabOld;
my $fstab;
my @fstabLines;
push @fstabLines, ['# <file system>', '<dir>', '<type>', '<options>', '<dump>', '<pass>'];
my @lengths = map {length($_)} @{$fstabLines[0]};
my $longestLine;

open(my $fh, '<'. $fstabFile) or die "Unable to open $fstabFile: $!\n";
while(defined(my $line =<$fh>))
{
    $fstabOld .= $line;
    $longestLine = (length($line) > $longestLine) ? length($line) : $longestLine;
    if ($line =~ m/^#/ and $line !~ m/<file system>/)
    {
        $fstab .= $line;
    }
    elsif ($line =~ m/^#/ and $line =~ m/<file system>/)
    {
        next;
    }
    else
    {
        $line =~ s/ +/ /g;
        my @fields = split ' ',$line;
        push @fstabLines, \@fields;
        for (my $i; $i < scalar @fields; $i += 1)
        {
            if (length($fields[$i]) > $lengths[$i])
            {
                $lengths[$i] = length($fields[$i]);
            }
        }
    }

}
close $fh;

my $printfStr = join '', map( {'%-'.($_+1).'s';} @lengths);

foreach my $line (@fstabLines)
{
    my @line = @{$line};
    $line = sprintf($printfStr, @line)."\n";
    $fstab .= $line;
    $longestLine = (length($line) > $longestLine) ? length($line) : $longestLine;
}

my $separator = ('-' x $longestLine)."\n";

print "\n",$separator, "ORIGINAL FILE\n", $separator, $fstabOld, $separator, "REFORMATTED FILE\n", $separator, $fstab, $separator;

print "Overwrite old file with new one? (y/n) ";
my $ans = <>;
chomp $ans;
if ($ans eq 'y')
{
    open(my $fh, '>', $fstabFile) or die "Unable to open $fstabFile: $!\n";
    print $fh $fstab;
    close $fh;
}
else
{
    print "Exiting without saving...\n";
    exit;
}