Perl (or something else) - ^ M problem

I am trying to add "at the beginning and ",at the end of each non-empty line a text file in Perl.

perl -pi -e 's/^(.+)$/\"$1\",/g' something.txt

It adds "at the beginning of each non-empty line, but I have a problem with ",.

Input Example:

bla
bla bla
blah

This output I get:

"bla
",
"bla bla
",
"blah
",

And for this conclusion, I really want :

"bla",
"bla bla",
"blah",

How to fix it?

Edit: I opened my output file in vim now (I opened it in kwrite before it was not visible), and I noticed that vim shows ^Mbefore each ",- I don’t know what the code adds this to.

0
source share
5 answers

Sounds like a line ending problem - did you edit the file in windows? Try dos2unix

dos2unix, \r:

perl -pi -e 's/^(.+)\r$/\"$1\",/g'

, , . *, :

"bla^M",
"bla bla^M",
"blah^M",
+5

Windows, CRLF , LF. , :

bla[CR][LF]bla bla[CR][LF]blah[CR][LF]

, od -c something.txt.

$ od -c something.txt
0000000    b   l   a  \r  \n   b   l   a       b   l   a  \r  \n   b   l
0000020    a   h  \r  \n                                                
0000024

Unix Linux :

bla\r
bla bla\r
blah\r

perl , :

"bla\r",
"bla bla\r",
"blah\r",

, , :

"bla
",
"bla bla
",
"blah
",

dos2unix Unix, , .

+2

, CRLF, Perl IO- CRLF, LF . , CRLF , CRLF, CRLF .

binmode. OO , , , YMMV:

use IO::File;

open( my $fh, '<', 'winfile.txt' ) 
    or die "Oh poo - $!\n";

$fh->binmode(':crlf');

:

open( my $fh, '<:crlf', 'winfile.txt' ) 
    or die "Oh poo - $!\n";

PERLIO (. PerlIO):

PERLIO=crlf perl -pi -e 's/^(.+)$/\"$1\",/g' something.txt

, CRLF , , .

+1

since you want to add at the beginning and end, you are not replacing the regex for this simple task.

perl -ne 'chomp;print "\"".$_."\",\n"' file
0
source

All Articles