Wednesday, December 29, 2021

[SOLVED] Insert a variable at line #1 of txt file using sed

Issue

I have the following bash:

#!/bin/bash
if ["$#" -ne "1"]; then
   echo "Usage: `basename $0` <HOSTNAME>"
   exit 1
fi

IPADDR=`ifconfig | head -2 | tail -1 | cut -d: -f2 | rev | cut -c8-23 | rev`
sed -i -e '1i$IPADDR   $1\' /etc/hosts

But when I cat /etc/hosts:

$IPADDR

How can I deal with such issues?


Solution

Your problem is that variables inside single quotes ' aren't expanded by the shell, but left unchanged. To quote variables you want expanded use double quotes " or just leave off the quotes if they are unneeded like here, e.g.

sed -i -e '1i'$IPADDR'   '$1'\' /etc/hosts

In above line $IPADDR and $1 are outside of quotes and will be expanded by the shell before the arguments are being feed to sed.



Answered By - Benjamin Bannier