Removing new line after a particular text via bash/awk/sed/perl

前端 未结 8 973
迷失自我
迷失自我 2021-01-02 00:22

I would like to remove all the newline character that occurs after a partiular string and replace it with a tab space. Say for instance my sample.txt is as follows



        
相关标签:
8条回答
  • 2021-01-02 00:30

    This might work for you:

    echo -e "foo\nbar bar bar bar some text"| sed '/foo$/{N;s/\n/\t/}'
    foo     bar bar bar bar some text
    

    Actually:

    echo -e "foo\nbar bar bar bar some text"| sed '/foo$/N;s/\n/\t/'
    foo     bar bar bar bar some text
    

    The latter solution is less efficient but not by much!

    0 讨论(0)
  • 2021-01-02 00:30

    Mmm. not sure this fits your requirements, but I'd do this in vim:

    :g/^foo$/join
    

    Or, if foo could be anywhere on a line:

    :g/foo$/join
    

    Of course, :%s/foo\n/foo\t/g will do nicely too

    0 讨论(0)
  • 2021-01-02 00:31

    The sed version looks like

    #!/bin/sed -f
    /foo/{
    N
    s/\n/\t/
    }
    

    If this is all you want to do in your sed command, you can simplify the above to a one-liner:

    sed -e '/foo/N;y/\n/\t/'  <sample.txt
    

    Explanation: N appends a newline and the next line of input; y/\n/\t replaces all newlines with tabs, or s/\n/\t/ replaces the first newline with a tab.

    Note that since sed is line-oriented, the newlines in the input are considered line-separators rather than as part of any line (this is in contrast e.g. to Perl).

    0 讨论(0)
  • 2021-01-02 00:31

    Not all tools can do newline replacement. Perl can:

    cat file.txt | perl -p -e 's/\n/ /g'
    
    0 讨论(0)
  • 2021-01-02 00:32
    perl -pe 's/(?<=foo)\n/\t/' input
    
    0 讨论(0)
  • 2021-01-02 00:34

    Here is how:

    cat input.txt | sed ':a;N;$!ba;s/foo\n/foo\t/g'
    

    More about why simple sed 's/foo\n/foo\t/g' does not work here: http://linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq5_009.html

    0 讨论(0)
提交回复
热议问题