Text Manipulation/Replacement
Rashkae
ubuntu at tigershaunt.com
Tue Sep 23 14:14:37 UTC 2008
Brian McKee wrote:
>>> cat foo.txt | perl -pi -e 's/\n//g'
>> This worked...kinda...but it ate all of the new lines, so I have one continuous line. I need to find all instances of "\n," and replace them with ",".
>
> cat foo.txt | perl -pi -e 's/\n/,/g' should work.
>
There is no reason to use cat. If you want to work with STDIN and
STDTOUT, use < > operators. example:
perl -p -e 'some code' < input.file > output.file
Or, if you use the i operator, that tells perl to edit the file in
place, so there's no reason to input / output
perl -pi -e 'some code' myfile.txt
This will overwrite your file with the changes.
And finally, the real problem, by default, perl only reads one line at a
time, so /n\, will never exist, because each input will end at /n and
the next input will begin with ,.
The quick and dirty way to solve this is to use -077 (zero seven seven).
That will put perl in file slurp mode, which means the input will take
the whole file, rather than one line at a time.
You have to be careful not to dos yourself with this command. If you
input a large enough file, it will all go into ram until you run out and
your computer crashes in unpredictable ways that depend on your kernel
version (most of them not pretty)
perl -pi -077 -e 's/\n,/,/g' myfile.txt
This command will do what you asked.
It will only nuke the /n if the next line begins with with a ,
More information about the ubuntu-users
mailing list