sed insert line with spaces to a specific line

后端 未结 4 1543
暖寄归人
暖寄归人 2021-01-30 16:01

I have a line with spaces in the start for example \" Hello world\". I want to insert this line to a specific line in a file. for example insert \" hello world\" to the next f

相关标签:
4条回答
  • 2021-01-30 16:14

    You can escape the space character, for example to add 2 spaces:

    sed -i "${line} i \ \ ${text}" $file
    

    Or you can do it in the definition of your text variable:

    text="\ \ hello world"
    
    0 讨论(0)
  • 2021-01-30 16:30
    $ a="  some string  "
    $ echo -e "hello\nworld"
    hello
    world
    $ echo -e "hello\nworld" | sed "/world/ s/.*/${a}.\n&/" 
    hello
      some string  .
    world
    

    The . was added in the substitution above to demonstrate that the trailing whitepsaces are preserved. Use sed "/world/ s/.*/${a}\n&/" instead.

    0 讨论(0)
  • 2021-01-30 16:32

    It can be done by splitting the expression like this:

    sed -i $file -e '2i\' -e "     $text"
    

    This is a GNU extension for easier scripting.

    0 讨论(0)
  • 2021-01-30 16:34

    You only need one \ to input multiple blanks like this

    sed -i "${line} i \    ${text}" $file
    
    0 讨论(0)
提交回复
热议问题