How to grep or awk or sed exact match in linux

Joined
Apr 16, 2023
Messages
149
Reaction score
16
Credits
1,460
Say I've
servername-server
servername
servername_new_bak


Say servername and servername_new_bak aren't running.

When I do
Code:
 ps -aux| grep servername | wc -l
I want only 1 as output as servername is not running, but currently I'm getting 3 as output because servername-server is running.
That's my use case.

How do I achieve this?
 


Working with a list from ls instead of ps (for ease of demonstration), is this the sort of thing you are after?:
Code:
[flip@flop ~]$ ls -al
total 8
drwxr-xr-x 2 flip flip 4096 Aug 21 20:27 .
drwxr-xr-x 6 flip flip 4096 Aug 21 20:26 ..
-rw-r--r-- 1 flip flip    0 Aug 21 20:27 servername
-rw-r--r-- 1 flip flip    0 Aug 21 20:27 servername_new_bak
-rw-r--r-- 1 flip flip    0 Aug 21 20:27 servername-server

[flip@flop ~]$ ls | grep servername$
servername

[flip@flop ~]$ ls | grep servername
servername
servername_new_bak
servername-server
 
Not sure what exactly you need but I understand it as you want result 1 or 0 depending on if one or more servername are running or no one is running. If this is what you want use:
Code:
ps -aux| grep servername | wc -l | awk '{ if($1>0) print 1; else print 0 }'
or
ps -aux| grep servername | wc -l | awk '{ if($1>0) print 0; else print 1 }'
depending on the logic for result 1 or 0 that you need

You always can optimize it and use only ps and awk because grep and wc are available inside awk but I leave this exercise to you.
 
If you want the exact name you should surround the text with both of the limiters:

some_command | grep ^servername$

But my advice would be different, in that way that:
Never choose a name that is part of another name already.
For example, when you have "servername", and then later create "servername2".
You can have "servername1" and "servername2", that is OK. ( But then don't create "servername10" !!! )

Thank me later ..
 

Staff online


Top