Insert newline (\n) using sed

前端 未结 4 1054
忘掉有多难
忘掉有多难 2020-12-03 04:23

I am trying to scrub some lists into a properly formatted CSV file for database import.

My starting file, looks something like this with what is supposed to be each &

相关标签:
4条回答
  • 2020-12-03 04:52

    Add a line after a match.

    The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found.

    sed '/unix/ a "Add a new line"' file.txt

    unix is great os. unix is opensource. unix is free os.
    
        "Add a new line"
        
        learn operating system.
        
        unixlinux which one you choose.
        
        "Add a new line"
    

    Add a line before a match

    The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.

    sed '/unix/ i "Add a new line"' file.txt

    "Add a new line"
    
    unix is great os. unix is opensource. unix is free os.
    
    learn operating system.
    
    "Add a new line"
    
    unixlinux which one you choose.
    
    0 讨论(0)
  • 2020-12-03 04:53

    The sed on BSD does not support the \n representation of a new line (turning it into a literal n):

    $ echo "123." | sed -E 's/([[:digit:]]*)\./\1\n next line/'
    123n next line
    

    GNU sed does support the \n representation:

    $ echo "123." | gsed -E 's/([[:digit:]]*)\./\1\nnext line/'
    123
    next line
    

    Alternatives are:

    Use a single character delimiter that you then use tr translate into a new line:

    $ echo "123." | sed -E 's/([[:digit:]]*)\./\1|next line/' | tr '|' '\n'
    123
    next line
    

    Or use an escaped literal new line in your sed script:

    $ echo "123." | sed -E 's/([[:digit:]]*)\./\1\
    next line/'
    123
    next line
    

    Or use awk:

    $ echo "123." | awk '/^[[:digit:]]+\./{sub(/\./,"\nnext line")} 1'
    123
    next line
    

    Or use GNU sed which supports \n

    0 讨论(0)
  • 2020-12-03 04:55

    The following works on Oracle Linux, x8664:

    $ echo 'foobar' | sed 's/foo/foo\n/'
    foo
    bar
    

    If you need it to match more than once per line, you'll need to place a g at the end, as in:

    $ echo 'foobarfoobaz' | sed 's/foo/foo\n/g'
    foo
    barfoo
    baz
    
    0 讨论(0)
  • 2020-12-03 05:10

    The portable way to get a newline in sed is a backslash followed by a literal newline:

    $ echo 'foo' | sed 's/foo/foo\
    bar/'
    foo
    bar
    

    I guarantee there's a far simpler solution to your whole problem by using awk rather than sed though.

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