Issue
I'm a bit troubled by grep
not behaving as expected.
I'm trying to extract hosts from a sort of dictionary, structured like OLD_HOST_NAME;NEW_HOST_NAME
, and some of them have the same prefix, like "HOST-1-2".
I want to only match "HOST-1-2", but independently from which option I pass to grep, it keeps returning all the strings with the same prefix instead of matching only the exact string, i.e.:
grep -F "HOST-1-2" dict.txt
HOST-1-2-3;NEW_HOST-1-2-3
HOST-1-2-4;NEW_HOST-1-2-4
HOST-1-2-5;NEW_HOST-1-2-5
I tried several options, like grep -w "HOST-1-2"
, grep -e '\HOST-1-2\b'
, grep -e '\HOST-1-2\b'
, grep -Po "\bHOST-1-2\b"
(that actually match what I want, but it does it for all occurrences of the substring so it's still not working), tried mixing them, but at the end of the day I'm still not getting what I need.
Any idea on how to achieve what I want, in order for grepping only "HOST-1-2" without all the other partial matches?
EDIT: Sorry to not have specified more clearly, the dictionary sample is the one I already shown as result of the wrong substring matching crep:
old_host;new_host
SERVER-1;NEW_SERVER-1
HOST-1-2-3;NEW_HOST-1-2-3
HOST-1-2-4;NEW_HOST-1-2-4
HOST-1-2-5;NEW_HOST-1-2-5
I already stated what I want to achieve though:
in order for grepping only "HOST-1-2" without all the other partial matches
Solution
You can use grep -o
to print only the matching part of the lines and add a word boundary after the 2
and before the H
grep -o '\<HOST-1-2\>' ./dict.txt
Output
HOST-1-2
HOST-1-2
HOST-1-2
If you only want to print the first matches:
grep -oP '^.*?\b\KHOST-1-2\b' ./dict.txt
Answered By - The fourth bird Answer Checked By - Robin (WPSolving Admin)