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

前端 未结 6 1000
伪装坚强ぢ
伪装坚强ぢ 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: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

提交回复
热议问题