0

I want to remove a newline character in a particular line through perl one-liner command.

Input:

1407233497,1407233514,bar
1407233498,1407233515,foo
mingstats&fmt=n
1407233499,1407233516,foobar

Expected output:

1407233497,1407233514,bar
1407233498,1407233515,foomingstats&fmt=n
1407233499,1407233516,foobar

What i tried so far?

This regex \n(?!\d+,\d+) matches exactly the newline that i want to remove. But i don't know how to implement it through perl one-liner command. I tried,

perl -pe 's/\n(?!\d+,\d+)//g' file

But it removes all the newline characters in that file and finally print the below in a single line,

1407233497,1407233514,bar1407233498,1407233515,foomingstats&fmt=n1407233499,1407233516,foobar

I will be so happy if the perl one-liner command uses above regex...

  • The (nice) quote you have on your home page doesn't come from Mark Twain. It is dirived from text in the song "Come from the heart" written by Leigh & Clark – Anthon Aug 29 '14 at 13:21
  • Good to Know. I'll change it soon.. – Avinash Raj Aug 29 '14 at 13:22
3

Try:

$ perl -00pe 's/\n(?!\d+,\d+)//g' file
1407233497,1407233514,bar
1407233498,1407233515,foomingstats&fmt=n
1407233499,1407233516,foobar

perl read file line by line by default with -p option, so your regex can not work.

-00 option turns paragraph slurp mode on, your regex now can work on multiline.

From perldoc perlrun:

-0[octal/hexadecimal]

specifies the input record separator ($/ ) as an octal or hexadecimal number. If there are no digits, the null character is the separator. Other switches may precede or follow the digits. For example, if you have a version of find which can print filenames terminated by the null character.

...

The special value 00 will cause Perl to slurp files in paragraph mode. Any value 0400 or above will cause Perl to slurp files whole, but by convention the value 0777 is the one normally used for this purpose

  • this also works perl -0007 -pe 's/\n(?!\d+,\d+)//' file. May i know what is -0007 and -p00e? – Avinash Raj Aug 29 '14 at 12:18
  • and also what is paragraph slurp mode? – Avinash Raj Aug 29 '14 at 12:19
  • +1 nice, may i know how to use dotall modifier (?s) in perl oneliner command? – Avinash Raj Aug 29 '14 at 12:53
  • get into here if you have time.. – Avinash Raj Aug 29 '14 at 13:20
2
perl -pe 'print "\n" if $c and !/^(?!\d+,\d+)/; $c=chomp; END{print "\n" if $c}' file_name
  • +1 for your effort.. May i know what is chomp , $c ? – Avinash Raj Aug 29 '14 at 15:45
  • chomp removes end of line mark. chomp without parameters operated on $_. chomp returns number of removed characters. $c variable in the above code stores information if previous line contained end of line mark. – AnFi Aug 29 '14 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.