-3

I want to create a unix/perl script to 30 spaces before printing the word. For Example:

Data:
Name                              Birthday
Michael Jordan                              Jan 1, 1800

Output file should filled-up the name and birthday column.

I need exact 30 spaces because the output file will be feed to mainframe program so the spaces are important.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

2 Answers2

2

If you're formatting for the mainframe, you may want to consider using pack. It will handle all of the nasty issues with forcing conformity to fixed-with output.

use strict;

my @output = (
  [ 'Name', 'Birthday' ],
  [ 'Michael Jordan', 'Jan 1, 1800' ],
  [ 'Lebron James', 'Jan 2, 1800' ],
  [ 'Hakeeeeeeeeem, The Dream Olajuwon', 'Jan 3, 1800' ]

);

foreach my $ref (@output) {
  print pack 'A30 A20 A1 A1', @$ref, '~', "\n";
}

Output:

Name                          Birthday            ~
Michael Jordan                Jan 1, 1800         ~
Lebron James                  Jan 2, 1800         ~
Hakeeeeeeeeem, The Dream OlajuJan 3, 1800         ~

I put the tilde (~) in there, just so you could see it was also padding the date.

Notice that Hakeeeeem's name was truncated to conform to the fixed-width.

Hambone
  • 15,600
  • 8
  • 46
  • 69
1

You can use Perl's x operator to replicate a string given number of times.

Examples:

perl -e 'print " "x30, $ARGV[0], "\n"' 'Name Birthday Michael Jordan Jan 1, 1800'

perl -ne 'print " "x30, $_' < datafile

yrk
  • 164
  • 9
  • Thanks yarek! I didn't know that we can specify the amount of character in print command. I will try your code. Thank you very much! – user3585505 Jul 30 '14 at 08:38
  • It Perl's built-in "`x`" operator which does the magic. I've extended the answer with this detail. – yrk Jul 30 '14 at 10:20