我正在尝试从 /etc/os-release 中提取操作系统名称,其中包含:
...
NAME="Os Name"
...
Run Code Online (Sandbox Code Playgroud)
但是当我执行时:
sed 's/.*NAME="\([^"]*\).*/\1/' /etc/os-release
Run Code Online (Sandbox Code Playgroud)
它正确捕获了操作系统名称,但它打印了所有其他行,而不是仅打印捕获的字符串,为什么?
os-release 文件的内容
cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"
CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"
Run Code Online (Sandbox Code Playgroud)
应该只输出“CentOS Linux”但它输出所有行的 sed 命令:
$ sed 's/.*NAME="\([^"]*\).*/\1/' /etc/os-release
CentOS Linux
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
CentOS Linux 7 (Core)
ANSI_COLOR="0;31"
cpe:/o:centos:centos:7
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"
CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"
Run Code Online (Sandbox Code Playgroud)
您可以在命令中使用-n选项来抑制常规输出和/p模式以s在特定行上打印结果:
sed -nE 's/^NAME="([^"]+)".*/\1/p' /etc/os-release
CentOS Linux
Run Code Online (Sandbox Code Playgroud)
您还可以使用 awk:
awk -F '["=]+' '$1=="NAME"{print $2}' /etc/os-release
CentOS Linux
Run Code Online (Sandbox Code Playgroud)
或使用grep -oP:
grep -oP '^NAME="\K[^"]+' /etc/os-release
Run Code Online (Sandbox Code Playgroud)