mlsmit10 has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

I'm a novice to perl, and I'm wondering if there is a way to add trailing spaces to all lines in a file that are less than x characters long in perl. I can do this in bash using the line:  awk '{printf("%-76s\n", $0)}' infile > outfile Where 76 is the number of characters I need to be in each line. I want to add this to a longer perl script. I'm sure there's an easy way to translate this into perl executable language, but I don't know it. Any help will be much appreciated!

Replies are listed 'Best First'.
Re: Trailing spaces to lines less than x characters
by toolic (Bishop) on Jun 05, 2015 at 16:32 UTC
    One way:
    use warnings; use strict; while (<DATA>) { chomp; my $len = length; $_ .= ' ' x (76 - $len) if $len < 76; print "$_\n"; } __DATA__ hfgjjasdgasdhgfask jhagfghfjkhsdg fjhsdfj fsf
Re: Trailing spaces to lines less than x characters
by Tux (Canon) on Jun 05, 2015 at 20:09 UTC
    $ perl -pe's/$/" "x(77-length)/e' file.txt

    Enjoy, Have FUN! H.Merijn
Re: Trailing spaces to lines less than x characters
by jeffa (Bishop) on Jun 05, 2015 at 16:45 UTC

    How about

    perl -ne'chomp; printf "%-76s\n", $_' infile > outfile

    Updated to correct silliness. Question: why do you need to append spaces to the end? That seems very impracticle ... spaces are usually prepended to such strings.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      That should be...

      perl -lne 'printf "%-76s", $_' infile > outfile

      ...otherwise the spaces will get appended after the newline on each existing line, and then another newline will be appended after that.

      Also in-place editing could look like this:

      perl -lni.bak -e 'printf "%-76s", $_' infile

      Dave

Re: Trailing spaces to lines less than x characters
by AnomalousMonk (Archbishop) on Jun 05, 2015 at 17:49 UTC

    If the padding is only for printing (i.e., output), one can also do:

    c:\@Work\Perl\monks>perl -wMstrict -le "use constant MIN => 5; ;; my $s = ''; for my $c ('', 'a' .. 'h') { $s .= $c; printf qq{%12s -> '%-*s' \n}, qq{'$s'}, MIN, $s; } " '' -> ' ' 'a' -> 'a ' 'ab' -> 'ab ' 'abc' -> 'abc ' 'abcd' -> 'abcd ' 'abcde' -> 'abcde' 'abcdef' -> 'abcdef' 'abcdefg' -> 'abcdefg' 'abcdefgh' -> 'abcdefgh'
    See sprintf for discussion of the  * format specifier.


    Give a man a fish:  <%-(-(-(-<

Re: Trailing spaces to lines less than x characters
by aaron_baugher (Curate) on Jun 05, 2015 at 18:59 UTC
    perl -pe 's/.*/$&." "x(76-$+[0])/e' <infile >outfile

    Aaron B.
    Available for small or large Perl jobs and *nix system administration; see my home node.