On May 25, 2:08 pm,
rvaede...@gmail.com wrote:
> I thought this would be easier to do this in perl.
>
> I have a file that doesn't have a field delimiter between the columns and I want to add a colon between each column. I can identify the columns by hard coding the range:
> such as "col1 to col 10" "col11 to col24" etc...
>
> I am stuck. Any advise would help. Thanks.
If the column ranges are guaranteed to be the same, you can do
something like:
my @fields = unpack("a10 a14", $line);
to extract out the fields in each column. Then you can re-print them
with colons in between them like this:
print join(':', @fields);
Here's a quick one-line solution. If you have a file (named
"input.txt") with these two lines:
1234567890abcdefghijklmn
happy day
Then running this one-liner:
# For Unix:
perl -wlne 'print join(":", unpack("a10 a14", $_))' input.txt
# For Windows/DOS:
perl -wlne "print join(':', unpack('a10 a14', $_))" input.txt
will get you this output:
1234567890:abcdefghijklmn
happy :day
Note that trailing spaces aren't stripped (you can see an example
of this this in the second line of output). If you want them to be
stripped, replace "a10 a14" with "A10 A14". Then your output will
look like:
1234567890:abcdefghijklmn
happy:day
You can look up the documentation for join() with "perldoc -f
join". You can read the documentation for unpack() with "perldoc -f
unpack". You can look up the letter templates (such as "a" and "A"
that you pass into unpack()) with "perldoc -f pack".
I hope this helps!
-- Jean-Luc