Bash 在文件中查找和替换不起作用,我做错了什么?

Bash find and replace in a file isn't working, what am I doing wrong?

我正在尝试用之前定义为变量 (n) 的不同 IP 替换文件 ("/etc/hosts") 中的所有 IP 地址(127.0.0.1 除外)。这是我拥有的:

grep -v '127.0.0.1' /etc/hosts | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | xargs -0 sed -i '$n'

如果有帮助,变量的默认赋值是 192.168.2.62。

我有点新手,所以无论你有什么见解都会很棒,谢谢!

您可以使用此 awk 命令代替所有管道命令:

awk -v n="$n" 'NF>1 &&  != "127.0.0.1" &&  ~ /^\d{1,3}\./ {=n} 1' /etc/hosts

您可以为此使用一个 sed 命令:

sed -r '/127.0.0.1/!{s/([0-9]{1,3}\.){3}[0-9]{1,3}/'"$n"'/}' file.txt

解释:

/127.0.0.1/                    Regex pattern
!                              The following block gets executed if 
                               the  previous regex does not match
{                              Start of block
s                              Start of `substitute` command
/([0-9]{1,3}\.){3}[0-9]{1,3}/  Regex pattern to match an ip 
                               (simplified!)
/'"$n"'/                       Replacement IP. Interpolation of $n
}                              End of block

如果您确定命令按预期工作,请添加 -i 选项。使用 -i 选项 sed 将修改原始文件 (file.txt)

您可以试试下面的 Perl 单行代码。

$ n="192.168.2.62"
$ echo '192.1.1.6 127.0.0.1 173.75.3.5' | perl -pe 's/\b(?!127\.0\.0\.1)[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b/'"$n/g"
192.168.2.62 127.0.0.1 192.168.2.62

添加内联编辑 -i 参数以保存所做的更改。

这对我有用 OSX:

find /etc/hosts -type f -exec sed -i '' '/^127\.0\.0\.1/! s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/192.192.192.192/g' {} \;

对于 Linux 以下应该有效:

find /etc/hosts -type f -exec sed -i '/^127\.0\.0\.1/! s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/192.192.192.192/g' {} \;

不确定 Linux 中花括号前是否需要额外的斜杠。

/^127\.0\.0\.1/! = 仅对不以 127.0.0.1

开头的行进行替换