使用Perl,如何用逗号替换换行符?

6 regex perl

我放弃了sed,我听说它在Perl中更好.

我想要一个可以从'unix'命令行调用的脚本,并CRLF从输入文件转换DOS行结尾,并用输出文件中的逗号替换它们:

喜欢

myconvert infile > outfile
Run Code Online (Sandbox Code Playgroud)

infile是:

1
2
3
Run Code Online (Sandbox Code Playgroud)

并将导致outfile:

1,2,3
Run Code Online (Sandbox Code Playgroud)

我希望更明确的代码与"尽可能短的解决方案"的一些最小的评论,所以我可以从中学习,我没有perl经验.

小智 28

在shell中,您可以通过多种方式执行此操作:

cat input | xargs echo | tr ' ' ,
Run Code Online (Sandbox Code Playgroud)

要么

perl -pe 's/\r?\n/,/' input > output
Run Code Online (Sandbox Code Playgroud)

我知道你希望这个更长,但我真的没有看到编写多行脚本来解决这么简单的任务 - 简单的regexp(在perl解决方案的情况下)是完全可行的,并且它不是人为缩短的东西 - 它是我将每天用来解决手头问题的代码类型.


Dea*_*vey 9

#!/bin/perl
while(<>) {      # Read from stdin one line at a time
    s:\r\n:,:g;  # Replace CRLF in current line with comma
    print;       # Write out the new line
}
Run Code Online (Sandbox Code Playgroud)


小智 6

use strict;
use warnings;

my $infile = $ARGV[0] or die "$0 Usage:\n\t$0 <input file>\n\n";
open(my $in_fh , '<' , $infile) or die "$0 Error: Couldn't open $infile for reading: $!\n";
my $file_contents;
{

    local $/; # slurp in the entire file. Limit change to $/ to enclosing block.
    $file_contents = <$in_fh>

}
close($in_fh) or die "$0 Error: Couldn't close $infile after reading: $!\n";

# change DOS line endings to commas
$file_contents =~ s/\r\n/,/g;
$file_contents =~ s/,$//; # get rid of last comma

# finally output the resulting string to STDOUT
print $file_contents . "\n";
Run Code Online (Sandbox Code Playgroud)

您的问题文本和示例输出不一致。如果您将所有行结尾都转换为逗号,那么从最后一行结尾开始,最后会有一个额外的逗号。但是您的示例仅显示数字之间的逗号。我假设您希望代码输出与您的示例相匹配,并且问题文本不正确,但是如果您想要最后一个逗号,只需删除带有注释“去掉最后一个逗号”的行。

如果有任何命令不清楚,http://perldoc.perl.org/是您的朋友(右上角有一个搜索框)。

  • 那真的很浪费,没有必要将整个文件放入内存中来查找和替换它:/ (9认同)