Question

I want to get all lines that are starting with a specific string, using awk.


I use the following code:
awk -v string="$string" '$0 ~ " "string {

if the $string=abc it will get all lines that have space abc space
that means the word abcd doesn't qualify

But I want to do it for words that are at the begging of the line. Meaning the " "string wont work.
So I need the character/sequence of characters that signal the start of a line

Was it helpful?

Solution

You can use line start anchor ^:

awk -v string="$string" '$0 ~ "^"string {

OTHER TIPS

This sounds like a job for grep:

grep "^$string"

but be aware that neither this grep nor the posted awk solutions are looking for a string, they are looking for a regexp.

To look for a line start starts with a string you need:

awk -v string="$string" 'index($0,string) == 1'

or if you want the string to be surrounded by nothing but blanks, simply:

awk -v string="$string" '$1 == string'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top