简体   繁体   English

如何为`perl -a`指定列分隔符?

[英]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: 我试图读取一个文本文件(使用perl),其中每行都有几条记录,如下所示:

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

So, & is the record separator. 因此, &是记录分隔符。

The Perl help says this: Perl帮助说:

$ 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: 但是046是分隔符&的八进制ASCII,因此我尝试了以下操作:

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". -0影响的记录分隔符是将输入划分为“行”的原因。 -a makes each "line" then be split into @F , by default on whitespace. -a使得每个“行”然后在@F默认分割为@F To change what -a splits on, use the -F switch, like -F'&' . 要更改-a分割的内容,请使用-F开关,如-F'&'

When in doubt about the perl command line options look at perldoc perlrun in the command line. 如果对perl命令行选项有疑问,请在命令行中查看perldoc perlrun

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. 另外,如果您使用-l选项perl -F'&' -lane ...它将在将每行的行尾(EOL)字符传递给脚本之前删除,并将其添加到每个打印件中,因此您无需在代码中添加“ \\ n”。 The fewer chars in a one liner the better. 一个衬里的字符越少越好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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