Sunday, February 27, 2022

[SOLVED] Replace path in specific line number of file

Issue

i have a file which contain :

 Source defaults file; edit that file to configure this script.
 
 AUTOSTART="all"
 
 STATUSREFRESH=10
 
 OMIT_SENDSIGS=0
 
 if test -e /etc/default/openvpn ; then
 
   . /etc/default/openvpn
 
 fi

i want to change the path /etc/default/openvpn in line 5 to /mnt/data/default/openvpn the same thing about line 6. I couldn't using sed -i '5s/etc/default...' , and with awk i can't replace the result in the file.

any one have a idea please ?

Thank you.

commands tried :

var1='/etc/default/openvpn'

var2='/mnt/data/default/openvpn'

sed -i '5s/'$var'/'$var2'/' files.txt

sed -i '5s/etc/default/openvpn/mnt/data/default/openvpn/' files.txt

sed -i '5s/'/etc/default/openvpn'/'/mnt/data/default/openvpn'/g' files.txt

awk 'NR==5 { sub("/etc/default/openvpn", "/etc/default/openvpn", $0); print }' files.txt

with awk, i can't save changes in the file


Solution

The issue here would be the delimiter in use as it will conflict with sed's default delimiter.

To resolve this, you can change the delimiter in use to any other character that does not appear in your data or escaping the default delimiter \/.

Using sed

$ sed -i.bak 's|/etc/default/openvpn|/mnt/data/default/openvpn|' input_file
$ cat input_file


    Source defaults file; edit that file to configure this script.

    AUTOSTART=all

    STATUSREFRESH=10

    OMIT_SENDSIGS=0

    if test -e /mnt/data/default/openvpn ; then

    . /mnt/data/default/openvpn

    fi


Answered By - HatLess
Answer Checked By - Pedro (WPSolving Volunteer)