![sed 或 awk 或 grep 获取字符串的第一次动态出现](https://linux22.com/image/11866/sed%20%E6%88%96%20awk%20%E6%88%96%20grep%20%E8%8E%B7%E5%8F%96%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E7%AC%AC%E4%B8%80%E6%AC%A1%E5%8A%A8%E6%80%81%E5%87%BA%E7%8E%B0.png)
从这个字符串
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/;.*//'