开发者

How to specify column separator for `perl -a`?

I'm trying to read a text file (using perl) where each line has several records, like this:

r1c1 & r1c2 & r1c3 \\
r2c1 & r2c2 & r2c3 \\

So, & is the record separator.

The Perl help says this:

$ perl -h 
  -0[octal]       specify record separator (\0, if no argument)

Why you would use octal number is beyond me. But 046 is the octal ASCII of the separator &, so I tried this:

perl -046 -ane 'print join ",", @F; print "\n"' file.txt

where the de开发者_如何学JAVAsired output would be

r1c1,r1c2,r1c3 \\
r2c1,r2c2,r2c3 \\    

But it doesn't work. How do you do it right?


I think you are mixing two separate things. The record separator that -0 affects is what divides the input up into "lines". -a makes each "line" then be split into @F, by default on whitespace. To change what -a splits on, use the -F switch, like -F'&'.


When in doubt about the perl command line options look at perldoc perlrun in the command line.

Also if you use the -l option perl -F'&' -lane ... it will remove the end-of-line (EOL) char of every line before pass it to your script and will add it for each print, so you don't need to put "\n" in your code. The fewer chars in a one liner the better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜