How to Display Lines That Starts With A Given String
Matching strings can be counted using grep, cat, sed. Matching strings can be sorted and even omitted for matching repetitions using sort and uniq. They can also be highlighted during the string parsing operation via grep. More can be done using awk. But have you ever tried to display the first occurrence of matching line that exactly begins or starts with the given search string?
Our objective is to display only the first line of occurrence that exactly begins with our matching string “blog linux” (shown in bold – 4th line), see below.
# cat testfile.txt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
blogger and blogger and linux blog linux
blogging linux blog linux redhat blog linux
blogging sysad blogs fedora linux blog linux
blog linux followed by any words
blogs linux sysad blog linux and blog linux
blogs sysad blog fedora blog linux
fedora blog systems blog linux
linux blog linux blog linux
sysad blog linux blog linux
sysad blogs linux blog linux
systems admin blog linux sysad blog linux
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Noticed that the word “blog linux” appeared several times from different lines of that text file. What we only need is the first occurrence of line that started with the word “blog linux” as our matching string.
Here’s how to display only those matching line from text file that exactly begins with given search string.
First, we need to sort the input text file like so
# cat testfile.txt | sort | uniq > output.txt
Then, let’s look that matching line that begins with our given search string “blog linux”. This would be done using linux look binary command.
# look -d “blog linux” output.txt
result:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
blog linux followed by any words
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
That is all
