sed with newlines and "

别来无恙 提交于 2019-12-13 05:55:11

问题


I have a bunch of textfile that looks like this:

His doctor attributed this to an allergy .

That hardly convinced him , as he had no history of allergies of any kind .
" Yet , that was to be the least of his problems .
I may have to take steroids for the rest of my life .
"
A topical steroid spray was later added to his repertoire of drugs and 
" he knew it was merely masking the underlying condition .
"

And I want to change it such that the . " are in a single line. The desired output should look like this:

His doctor attributed this to an allergy .

That hardly convinced him , as he had no history of allergies of any kind .
" Yet , that was to be the least of his problems .
I may have to take steroids for the rest of my life . "
A topical steroid spray was later added to his repertoire of drugs and 
" he knew it was merely masking the underlying condition . "

I've tried this but it doesn't work:

sed -i 's/.\n"\n/. "\n/g'

Can someone help me out on the correct sed command to shift the " up?


回答1:


This is what I figured out:

sed -n '1{h;d};/^"$/{g;s/$/ "/p;n;h;d};x;p;${g;p}' input.txt

output

His doctor attributed this to an allergy .

That hardly convinced him , as he had no history of allergies of any kind .
" Yet , that was to be the least of his problems .
I may have to take steroids for the rest of my life . "
A topical steroid spray was later added to his repertoire of drugs and
" he knew it was merely masking the underlying condition . "



回答2:


perl -00 -lpe 's/\n"$/"/mg'

produces the desired output.




回答3:


A slightly different sed variant:

sed -n '1{h};1!{/"$/!H};/"$/{H;g;s/\.[ \n]*"$/\. "/;p;n;x}' input.txt
  • 1 { h } — put first line into the hold buffer
  • 1! { /"$/ !H } — for the rest of the lines, accumulate into hold buffer if no lonely "
  • /"$/ { H; g; s/\.[ \n]*"$/\. "/; p; n; x } — otherwise:

    1. H — add to the hold buffer
    2. g — move hold buffer to the pattern space
    3. s/\.[ \n]*"$/\. "/ — do the replacement
    4. p — print it out
    5. n — read next line
    6. x — and keep it in the hold buffer



回答4:


This might work for you:

sed ':a;$!N;s/\.\n"/."/;P;D' /tmp/a
His doctor attributed this to an allergy .

That hardly convinced him , as he had no history of allergies of any kind ." Yet , that  was to be the least of his problems .
I may have to take steroids for the rest of my life ."
A topical steroid spray was later added to his repertoire of drugs and 
" he knew it was merely masking the underlying condition ."


来源:https://stackoverflow.com/questions/10318189/sed-with-newlines-and

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!