How do I add a line of text to the middle of a file using bash?

前端 未结 6 967
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 22:28

I\'m trying to add a line of text to the middle of a text file in a bash script. Specifically I\'m trying add a nameserver to my /etc/resolv.conf file. As it stands, resol

相关标签:
6条回答
  • 2020-12-02 23:02

    awk '/^nameserver/ && !modif { printf("INSERT\n"); modif=1 } {print}'

    0 讨论(0)
  • 2020-12-02 23:05

    Assuming you want to insert immediately after the search line, this is much simpler:

    sed -ie '/^search/a nameserver 127.0.0.1' filename
    
    • -i : edit file in place
    • -e : allows the execution of a script/commands inside sed expression
    • a mynewtext : command that tells sed to insert the text mynewtext after matched pattern
    0 讨论(0)
  • 2020-12-02 23:06

    Here's a Perl solution:

    perl -lne 'if (not $f and /^nameserver/){ print "nameserver 127.0.0.1"; $f=1 }; print' resolv.conf

    • -n loop around every line of the input file, do not automatically print every line

    • -l removes newlines before processing, and adds them back in afterwards

    • -e execute the perl code

    $f is used as a flag to indicate that the nameserver string has already been found

    0 讨论(0)
  • 2020-12-02 23:10

    Here is a solution using sed:

    $ sed -n 'H;${x;s/^\n//;s/nameserver .*$/nameserver 127.0.0.1\n&/;p;}' resolv.conf
    
    # Generated by NetworkManager
    domain dhcp.example.com
    search dhcp.example.com
    nameserver 127.0.0.1
    nameserver 10.0.0.1
    nameserver 10.0.0.2
    nameserver 10.0.0.3
    

    How it works: first, suppress the output of sed with the -n flag. Then, for each line, we append the line to the hold space, separating them with newlines:

    H
    

    When we come to the end of the file (addressed by $) we move the content of the hold space to the pattern space:

    x
    

    If the first line in pattern space is blank we replace it with nothing.

    s/^\n//
    

    Then we replace the first line starting with nameserver by a line containing nameserver 127.0.0.1, a new line (Your version of sed may not support \n, in which case replace the n with a literal newline) and the original line (represented by &):

    s/nameserver .*$/nameserver 127.0.0.1\n&/
    

    Now we just need to print the results:

    p
    
    0 讨论(0)
  • 2020-12-02 23:12

    How about something like:

    sed -e ':a;N;$!ba;s/nameserver/nameserver 127.0.0.1\nnameserver/' /etc/resolv.conf
    

    (similar to this: sed: Find pattern over two lines, not replace after that pattern)

    0 讨论(0)
  • 2020-12-02 23:16

    This might work for you:

     sed -e '/nameserver/{x;/./b;x;h;i\nameserver 127.0.0.1' -e '}' resolv.conf
    

    Or GNU sed:

    sed -e '0,/nameserver/{//i\nameserver 127.0.0.1' -e '}' resolv.conf
    
    0 讨论(0)
提交回复
热议问题