Script to display only comments from /etc/services file

Viewed 95

I need to write a bash script that takes service name as a parameter and display only comment that is after hash symbol in /etc/services but I have no idea how to cut only the comment part.

The ,,it's working solution'' for me is to just:

grep "^$1" /etc/services | awk '{print $3,$4 ...

but I don't think this is a good one

I'm searching for something like:

[find the service] -> print only the part from # till the end of the line

I'm still learning so any solution with explanation or just a hint will be very helpful for me.

2 Answers

Chances are this is what you're looking for:

awk -v svc="$1" '($1==svc) && sub(/[^#]+#/,"")' /etc/services

but without sample input/output it's a guess.

The above will work using any awk in any shell on every Unix box.

Try this:

SERVICE_NAME=linuxconf; grep -Po "^$SERVICE_NAME.*# \K.*$" /etc/services

-P tells grep to use perl regex.

-o trims the output so that it only includes the regex match.

\K tells the regex engine to exclude previously matched part of the string from the match, i.e. only the part after \K will be present in the final match.

Related