简体   繁体   中英

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 desired 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM