简体   繁体   English

使用 sed 在 txt 文件的第 1 行插入一个变量

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

I have the following bash:我有以下 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 :但是当我cat /etc/hosts

$IPADDR

How can I deal with such issues?我该如何处理此类问题?

Your problem is that variables inside single quotes ' aren't expanded by the shell, but left unchanged. 您的问题是单引号'中的变量不会被shell扩展,而是保持不变。 To quote variables you want expanded use double quotes " or just leave off the quotes if they are unneeded like here, eg 要引用您要扩展的变量,请使用双引号"或者,如此处不需要,请省略引号,例如

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 . 在上面的行中, $IPADDR$1在引号之外,并在将参数提供给sed之前由shell进行扩展。

The single quotes mean the string isn't interpolated as a variable. 单引号表示字符串不会作为变量插入。

#!/bin/bash
IPADDR=$(/sbin/ifconfig | head -2 | tail -1 | cut -d: -f2 | rev | cut -c8-23 | rev)
sed -i -e "1i${IPADDR}   ${1}" /etc/hosts

I also did the command in $(...) out of habit! 我也出于习惯在$(...)了命令!

Refer to sed manual: https://www.gnu.org/software/sed/manual/sed.html参考 sed 手册: https : //www.gnu.org/software/sed/manual/sed.html

As a GNU extension, the i command and text can be separated into two -e parameters, enabling easier scripting:作为 GNU 扩展,i 命令和文本可以分成两个 -e 参数,从而更容易编写脚本:

The formal usage should be:正式的用法应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM