The purpose of the command should be replacing any IP in file myfile.txt with the local ip of the server automatically


sed -i -e 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/LOCALIP/g' myfile.txt

i want to know if it possible to use command for getting local ip address inside sed

basically i want to replace LOCALIP in my example with this command

/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1 

You can use command substitution in double quotes:

sed -i -e 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/'"$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)/g" myfile.txt

In single quotes, this won't work, so end the single quotes before LOCALIP, use double quotes for the command. This way, we don't accidentally do expansions in the search pattern.

  • Thank you for quick answer, got this error : sed: -e expression #1, char 71: unterminated `s' command – Ali EL KANDOUSSI Nov 21 '18 at 14:54
  • Are you sure the command to get IP is executing correctly? What output do you get with /sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)? Also, try putting an echo before sed to see what sed command is finally run. – user321727 Nov 21 '18 at 15:02
  • Got this output with /sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1): – Ali EL KANDOUSSI Nov 21 '18 at 15:12
  • @JeffSchaller but "$(...)"/g and "$(...)/g" should both give the same string, shouldn't it? – user321727 Nov 21 '18 at 15:27
  • 1
    Appears the OP has a space - separated list of two IP's coming back from that command, causing the sed command to end early. – Jeff Schaller Nov 21 '18 at 16:12

Below command worked fine for me

sed "s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)/"

i solved my issue with this command

sed -i "s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/$(ifconfig | grep 'inet ' | grep -v '' | awk '{print $2}')/" myfile.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.