0

I am trying to replace this command:

HOST_IP_ADDRESS=$(/sbin/ifconfig  | grep inet | grep -v 127.0.0.1 | awk '{print $2}' | cut -d)

in my multipile script file in a single try. I greped the output through

 grep -R 'HOST_IP_ADDRESS' ./ -R | grep "127.0.0.1" | awk -F ":" '{print $2}'

I want to replace the result with HOST_IP_ADDRESS=hostname -i instead of

HOST_IP_ADDRESS=$(/sbin/ifconfig  | grep inet | grep -v 127.0.0.1 | awk '{print $2}' | cut -d

is their any way do this through sed command.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Savio Mathew
  • 719
  • 1
  • 7
  • 14
  • As I already mentioned in the linked question, please be aware that all the `hostname` tips/answers will most likely fail on anything else than **GNU's** `hostname` implementation, as on almost all other flavors of Unix this tool is meant to **set** the hostname instead of looking up funny things. To my knowledge, this includes OSX, *BSD, Solaris and probably a lot more. So relying on this behavior will result in non-portable code. – he1ix Jul 08 '14 at 12:39

3 Answers3

0

Why do you want to use sed? Maybe you could use this alternative solution:

HOST_IP_ADDRESS=$(hostname -I | cut -f1 -d' ')

See Putting IP Address into bash variable. Is there a better way

Community
  • 1
  • 1
Kokkie
  • 546
  • 6
  • 15
0

If I understood you well you want to replace this:

HOST_IP_ADDRESS=$(/sbin/ifconfig  | grep inet | grep -v 127.0.0.1 | awk '{print $2}' | cut -d)

by:

HOST_IP_ADDRESS=$(hostname -i)

Which is a bit hard because of the characters that need to be escaped, take a look at the script below:

#! /bin/bash

o='HOST_IP_ADDRESS=$(/sbin/ifconfig  | grep inet | grep -v 127.0.0.1 | awk '\''{print $2}'\'' | cut -d)'
n='HOST_IP_ADDRESS=$(hostname -i)'

echo "$o" > file
sed -e 's#'"$o"'#'"$n"'#g' file

Its output:

bash  test.sh 
HOST_IP_ADDRESS=$(hostname -i)

cat file
HOST_IP_ADDRESS=$(/sbin/ifconfig  | grep inet | grep -v 127.0.0.1 | awk '{print $2}' | cut -d)

It's all about how you escape things, as you can see this script creates a file containing the old string in $o then it replaces by the new string $n, if you want to modify the file use -i.bak instead of -e for sed to ensure you make a backup

Tiago Lopo
  • 7,619
  • 1
  • 30
  • 51
0

This will edit your files in-place, replacing the ifconfig hack with $(hostname -i):

sed -i -e 's/\(HOST_IP_ADDRESS=\).*/\1$(hostname -i)/' filenames-go-here

Make backups first.

Actually it will not just replace the ifconfig hack, it will replace any lines beginning with HOST_IP_ADDRESS=

Peder Klingenberg
  • 37,937
  • 1
  • 20
  • 23