从这个字符串
Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)
我想获得(并在 shell 中打印)“...apache2.service;”之后的第一个匹配项该词可以“启用”或“禁用”
我如何使用 grep 或 sed 或 awk 来获取它?
答案1
使用SED:
echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | sed -n 's/.*service; \([^;]*\).*/\1/p'
使用格雷普:
echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | grep -o -P '(?<=service; ).*(?=;)'
使用AWK:
echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | awk -F 'service; |;' '{print $2}'
service;
将打印和之间的字符串;
答案2
您可以使用awk
echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | awk '{print $4}'
或者awk
echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | awk -v RS=" " '/service/{getline;print "",$0}' | tr -d ";"
或者cut
echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | cut -d';' -f 2
或在两个分号之间sed
提取disable
echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | sed 's/^[^;]*;//; s/;.*//'