Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

perl - Preserving blank columns & adding delimiters when reading fixed width data

I am parsing through a file.

The file format is like this:


Column1  Column2  Column3  Column4  Column5
1        2        3        4        5
6        7                 8        9
10       11       12                14
         15       16       17       18

Some of the Column's are empty. So I am reading two files having same format as above and merging both files and adding the "|" between each column so it should look like this:


Column1 | Column2 | Column3 | Column4 | Column5
1       | 2       | 3       | 4       | 5
6       | 7       |         | 8       | 9
10      | 11      | 12      |         | 14
        | 15      | 16      | 17      | 18

But I'm getting like this. The spaces in columns are removed.


Column1 | Column2 | Column3 | Column4 | Column5
1       | 2       | 3       | 4       | 5
6       | 7       | 8       | 9
10      | 11      | 12      | 14
15      | 16      | 17      | 18

Code part:

while(<FH>){
   my @lines =split ' ',$_;
   say (join '|',@lines);
}

I know this is happening because I am splitting with space delimiter. Can anyone tell me how to get the desired output?

question from:https://stackoverflow.com/questions/65864154/preserving-blank-columns-adding-delimiters-when-reading-fixed-width-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use unpack to parse fixed-width data. The A9 in the template assumes your columns are 9 characters wide. You can use sprintf to space the data out again into columns of the original width.

use warnings;
use strict;

while (<DATA>) {
    chomp;
    printf "%s
", join '| ', map { sprintf '%-8s', $_ } unpack 'A9' x 5, $_;
}

__DATA__
Column1  Column2  Column3  Column4  Column5
1        2        3        4        5
6        7                 8        9
10       11       12                14
         15       16       17       18

This prints:

Column1 | Column2 | Column3 | Column4 | Column5 
1       | 2       | 3       | 4       | 5       
6       | 7       |         | 8       | 9       
10      | 11      | 12      |         | 14      
        | 15      | 16      | 17      | 18      

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...