Aligning columns in a text file using Perl


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Aligning columns in a text file using Perl
# 1  
Old 04-06-2012
Aligning columns in a text file using Perl

Hi All,

I am new to perl and was trying to write a simple program which will generate a text file as output..

now the output which i am getting is something like this..

Code:
==================================================================================================
Col1                                         |                     Col2
==================================================================================================
value1                                                            Updated this row
value1                                                            Updated this row also
value1                                                            Updated again
value1                                                            Changed table contents
value-value-value-value-value2                                  added few lines of code
value-value-value-value-value2                                  added another few lines using perl
ABCDEFGH                                                updated code to add few lines
TESTING                                              added new testing procedure
TESTING AGAIN                                                  Updated General info
ABCDEFG TESTING, AGAIN AND AGAIN                                      Updated information
ABCDEFG TESTING, AGAIN AND AGAIN                                      Updated home address
==================================================================================================

the code i am using to get the above output is

Code:
printf MY_FILE ( "%s \t\t\t\t\t %-20s\n",$title,$desc);

i want output to be in this pattern

Code:
==================================================================================================
Col1                                                      | Col2
==================================================================================================
value1                                                    | Updated this row
value1                                                    | Updated this row also
value1                                                    | Updated again
value1                                                    | Changed table contents
value-value-value-value-value2                            | added few lines of code
value-value-value-value-value2                            | added another few lines using perl
ABCDEFGH                                                  | updated code to add few lines
TESTING                                                   | added new testing procedure
TESTING AGAIN                                             | Updated General info
ABCDEFG TESTING, AGAIN AND AGAIN                          | Updated information
ABCDEFG TESTING, AGAIN AND AGAIN                          | Updated home address
==================================================================================================

please help me to get this output in alligned manner!!
# 2  
Old 04-06-2012
Hi smarty86,

Somthing like:
Code:
printf MY_FILE "%-50s | %-30s\n", $title, $desc

This User Gave Thanks to birei For This Post:
# 3  
Old 04-08-2012
Thanks buddy.. This is working great,..

Now if I want to limit no. of characters in first columns to somevalue and if it exceeds that many characters then it should go to next line.. how can i do that?

like
Code:
==================================================================================================
Col1                                                      | Col2
==================================================================================================
value1                                                    | Updated this row
value1                                                    | Updated this row also
value1                                                    | Updated again
value1                                                    | Changed table contents
value-value-value-value
-value2                            			  | added few lines of code
value-value-value-value
-value2                            			  | added another few lines using perl
ABCDEFGH                                                  | updated code to add few lines
TESTING                                                   | added new testing procedure
TESTING AGAIN                                             | Updated General info
ABCDEFG TESTING, AGAIN 
AND AGAIN                          		          | Updated information
ABCDEFG TESTING, AGAIN 
AND AGAIN                          		          | Updated home address
==================================================================================================

the value in the 5,6,10,11 rows in the first column is writted in 2 lines... appreciate your help thank you
# 4  
Old 04-08-2012
How about this ?

Code:
 
#!/usr/bin/perl
$col1_limit=15;
$col2_limit=30;
$j=0;
while (<DATA>) {
        chomp;
        ($title,$desc)=split;
        if (length($title) <=15) { printf "%-${col1_limit}s | %-${col2_limit}s\n",$title,$desc;next}
        for($i=1;$i<=((length($title))/$col1_limit);$i++){
                printf "%-${col1_limit}s | %-${col2_limit}s\n",substr($title,$j,$col1_limit),$desc if ($i==1);
                printf "%-${col1_limit}s\n",substr($title,$j,$col1_limit);
                $j+=$col1_limit;
        }
        if (length($title) > $j) {printf "%-${col1_limit}s\n",substr($title,$j);}
        $j=0;

}
__DATA__
value1                                                            Updated this row
value1                                                            Updated this row also
value1                                                            Updated again
value1                                                            Changed table contents
value-value-value-value-value2                                  added few lines of code
value-value-value-value-value2---                                  added another few lines using perl
ABCDEFGH                                                updated code to add few lines
TESTING                                              added new testing procedure
TESTING AGAIN                                                  Updated General info
ABCDEFG TESTING, AGAIN AND AGAIN                                      Updated information
ABCDEFG TESTING, AGAIN AND AGAIN                                      Updated home address

This User Gave Thanks to pravin27 For This Post:
# 5  
Old 04-08-2012
Thanks buddy working as expected... thanks again.. u guys are very helpful Smilie
# 6  
Old 04-19-2012
hi praveen and others..

whatever u told above was ok but now the problem is i need to check only in 1st column and only if the characters exceeds 36 then it should go to next line in the same column... and in 2nd column the seperator(|) should come just infront of the 2nd line.. pls help..
Code:
ABCDE FGHI, JKLMNOP, ABCDEFGHa nabsd 
AND DONE                                                   | Added for testing

---------- Post updated 04-18-12 at 07:13 PM ---------- Previous update was 04-17-12 at 11:21 PM ----------

Quote:
Originally Posted by smarty86
hi praveen and others..

whatever u told above was ok but now the problem is i need to check only in 1st column and only if the characters exceeds 36 then it should go to next line in the same column... and in 2nd column the seperator(|) should come just infront of the 2nd line.. pls help..
Code:
ABCDE FGHI, JKLMNOP, ABCDEFGHa nabsd 
AND DONE                                                   | Added for testing


pls help me guys
# 7  
Old 04-19-2012
Did you solve it?

I think it is not the exact solution you are looking for, but perhaps it helps. I use a non built-in module, you will have to install it using CPAN or similar tool. Also adjust column width to your needs, I used 10 characters for the example.
Code:
$ cat script.pl
use warnings;
use strict;
use Text::ASCIITable;

my @lines;
my @header = qw( col1 col2 );

while ( <DATA> ) {
        chomp;
        my @f = map { s/\s+\Z//; $_ } split /\|/;
        push @lines, [ @f ];
}

my $t = Text::ASCIITable->new;
$t->setCols( @header );

$t->setColWidth( $header[0], 10 );
for ( @lines ) {
        $_->[0] =~ s/(.{10})(?=\S)/$1\n/g;
        my $num_lines = $_->[0] =~ tr/\n/\n/;
        for my $i ( 1 .. $num_lines ) {
                $_->[1] =~ s/^/\n/;
        }
        $t->addRow( $_ );
}

print $t;

__DATA__
value1                                                    | Updated this row
value1                                                    | Updated this row also
value1                                                    | Updated again
value1                                                    | Changed table contents
value-value-value-value-value2                            | added few lines of code
value-value-value-value-value2                            | added another few lines using perl
ABCDEFGH                                                  | updated code to add few lines
TESTING                                                   | added new testing procedure
TESTING AGAIN                                             | Updated General info
ABCDEFG TESTING, AGAIN AND AGAIN                          | Updated information
ABCDEFG TESTING, AGAIN AND AGAIN                          | Updated home address
$ perl script.pl
.--------------------------------------------------.
| col1       | col2                                |
+------------+-------------------------------------+
| value1     |  Updated this row                   |
| value1     |  Updated this row also              |
| value1     |  Updated again                      |
| value1     |  Changed table contents             |
| value-valu |                                     |
| e-value-va |                                     |
| lue-value2 |  added few lines of code            |
| value-valu |                                     |
| e-value-va |                                     |
| lue-value2 |  added another few lines using perl |
| ABCDEFGH   |  updated code to add few lines      |
| TESTING    |  added new testing procedure        |
| TESTING AG |                                     |
| AIN        |  Updated General info               |
| ABCDEFG TE |                                     |
| STING, AGA |                                     |
| IN AND AGA |                                     |
| IN         |  Updated information                |
| ABCDEFG TE |                                     |
| STING, AGA |                                     |
| IN AND AGA |                                     |
| IN         |  Updated home address               |
'------------+-------------------------------------'

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Aligning a file

I have a large text file in following format cat input.txt abc qwert qwer afweferf wdfwefwe ==> kjhjkwdd mnmn ==> jkjkjwekj poiu ==> lklklke tytyutut ==> olkjmnsmn I need to align those lines with the characters " ==>" . I dont want to disturb the lines which dont have "==>". The... (6 Replies)
Discussion started by: ctrld
6 Replies

2. Shell Programming and Scripting

Perl syntax for formatting columns and text

Dear all, Pzl let me know what is the syntax for converting the columns format to text as i have lots of values for but when i put these values in xls sheet the values are automatically converted to and one more question i have is how to call values from shell script into perl script eg. ... (3 Replies)
Discussion started by: sagar_1986
3 Replies

3. Shell Programming and Scripting

How to concatenate 2-columns by 2 -columns for a text file?

Hello, I want to concatenate 2-columns by 2-columns separated by colon. How can I do so? For example, I have a text file containing 6 columns separated by tab. I want to concatenate column 1 and 2; column 3 and 4; column 5 and 6, respectively, and put a colon in between. input file: 1 0 0 1... (10 Replies)
Discussion started by: huiyee1
10 Replies

4. Shell Programming and Scripting

Replace text in column1 of a file matching columns of another file

Hi all, I have 2 files: species-names.txt Abaca-bunchy-top-virus ((((Abaca-bunchy-top-virus((Babuvirus((Unassigned((Nanoviridae((Unassigned)))) Abutilon-mosaic-virus ((((Abutilon-mosaic-virus((Begomovirus((Unassigned((Geminiviridae((Unassigned))))... (2 Replies)
Discussion started by: thienxho
2 Replies

5. UNIX for Dummies Questions & Answers

Help with Aligning the content of a txt file

Hello friends Please help me to display the content of a file in specific aligned manner. for ex. the content of the file may be >$TEST WELCOME HI HELLO UNIX SHELL SCRIPTING >$ I want to display the content like . TEST WELCOME HI HELLO ... (18 Replies)
Discussion started by: rajmohan146
18 Replies

6. UNIX for Dummies Questions & Answers

Perl - adding columns to file

I have a file in which I need to add more columns to based on a key in the first file: File1 key1,abc,123, key2,def,456, key3,ghi,789, File2 key2,zyx,111,qqq, key3,yuu,222,www, key1,pui,333,eee, key4,xxx,999,rrr, I would like to create the following output: Output (1 Reply)
Discussion started by: WongSifu
1 Replies

7. UNIX for Dummies Questions & Answers

Removing columns from a text file that do not have any values in second and third columns

I have a text file that has three columns. But at the end of the text file, there are trailing lines that have missing second and third columns: 4 0.04972604 KLHL28 4 0.0497332 CSTB 4 0.04979822 AIF1 4 0.04983331 DECR2 4 0.04990344 KATNB1 4 4 4 4 How can I remove the trailing... (3 Replies)
Discussion started by: evelibertine
3 Replies

8. Shell Programming and Scripting

Aligning numbers in the second file based on first file

Hi All, I have two sets of files with names .dat and .txt. The number of files is really large more than 90000. The files have names like 1.dat, 2.dat,3.dat and so on where as txt files have names like 1.txt, 2.txt, 3.txt and so on The DAT and TXT files are equal in number. About 90000 each ... (4 Replies)
Discussion started by: shoaibjameel123
4 Replies

9. Shell Programming and Scripting

Aligning text files by max field length

Hello, Is there anyway that I can align a pipe delimited text file by the maxium field length where the field is separated out by pipes for large text files with more than 100,000 rows? So, far I have searched other forums and google about aligning text files in unix and I have noticed that... (7 Replies)
Discussion started by: physalis2099
7 Replies

10. UNIX for Dummies Questions & Answers

How to convert text to columns in tab delimited text file

Hello Gurus, I have a text file containing nearly 12,000 tab delimited characters with 4000 rows. If the file size is small, excel can convert the text into coloumns. However, the file that I have is very big. Can some body help me in solving this problem? The input file example, ... (6 Replies)
Discussion started by: Unilearn
6 Replies
Login or Register to Ask a Question