0

from this string

Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)

I want to get (and to print in shell) the first match after "...apache2.service;" This word can be "enabled" or "disabled"

How can I use grep or sed or awk to get it?

2
  • 5
    Sounds like a XY question... Are you actually trying to get the state of systemd unit ? Oct 1, 2018 at 18:24
  • 3
    systemctl is-enabled apache2 should print enabled or disabled. Similarly, systemctl is-active apache2 should print active or inactive. Also, see similar use-case for is-failed.
    – ILMostro_7
    Oct 1, 2018 at 18:46

2 Answers 2

0

Using SED:

echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | sed -n 's/.*service; \([^;]*\).*/\1/p'

Using Grep:

echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | grep -o -P '(?<=service; ).*(?=;)'

Using AWK:

echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | awk -F 'service; |;' '{print $2}'
  • will print the string between service; and ;
2
  • thank you so much, for the examples and right way to check systemctl
    – Lilia
    Oct 2, 2018 at 16:28
  • @Lilia you could accept the answer if it works..
    – Siva
    Oct 2, 2018 at 17:52
0

you can use awk

 echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | awk '{print $4}'

or awk

echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | awk -v RS=" " '/service/{getline;print "",$0}' | tr -d ";"

or cut

echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | cut -d';' -f 2

or sed to extract disable between two semi-colons

 echo "Loaded: loaded (/lib/systemd/system/<name>.service; disabled; vendor preset: enabled)" | sed 's/^[^;]*;//; s/;.*//'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .