grep on a variable

331,748

Solution 1

Have grep read on its standard input. There you go, using a pipe...

$ echo "$line" | grep select

... or a here string...

$ grep select <<< "$line"

Also, you might want to replace spaces by newlines before grepping :

$ echo "$line" | tr ' ' '\n' | grep select

... or you could ask grep to print the match only:

$ echo "$line" | grep -o select

This will allow you to get rid of the rest of the line when there's a match.

Edit: Oops, read a little too fast, thanks Marco. In order to count the occurences, just pipe any of these to wc(1) ;)

Another edit made after lzkata's comment, quoting $line when using echo.

Solution 2

test=$line i=0
while case "$test" in (*select*)
test=${test#*select};;(*) ! :;;
esac; do i=$(($i+1)); done

You don't need to call grep for such a simple thing.

Or as a function:

occur() while case "$1" in (*"$2"*) set -- \
        "${1#*"$2"}" "$2" "${3:-0}" "$((${4:-0}+1))";;
        (*) return "$((${4:-0}<${3:-1}))";;esac
        do : "${_occur:+$((_occur=$4))}";done

It takes 2 or 3 args. Providing any more than that will skew its results. You can use it like:

_occur=0; occur ... . 2 && echo "count: $_occur"

...which prints the occurrence count of . in ... if it occurs at least 2 times. Like this:

count: 3

If $_occur is either empty or unset when it is invoked then it will affect no shell variables at all and return 1 if "$2" occurs in "$1" fewer than "$3" times. Or, if called with only two args, it will return 1 only if "$2" is not in "$1". Else it returns 0.

And so, in its simplest form, you can do:

occur '' . && echo yay || echo shite

...which prints...

shite

...but...

occur . . && echo yay || echo shite

...will print...

yay

You might also write it a little differently and omit the quotes around $2 in both the (*"$2"*) and "${1#*"$2"}" statement. If you do that then you can use shell globs for matches like sh[io]te for the match test.

Share:
331,748

Related videos on Youtube

gkmohit
Author by

gkmohit

I am an Entrepreneur, Web Designer and Online Business Consultant. My mission is to help small businesses grow by leveraging the power of the internet. I believe in automating tasks by using tools so that you can focus on your core business. I have always been a curious person. The first time I used a computer was in grade 8 and fascinated by how you could create digital art using Corel Draw. In class 10, I had the opportunity to use the first mobile phone, and I was very intrigued by how the OS integrated with the hardware. That same curiosity led me to write my first piece of code in grade 10, and I then realized the power a programmer had in this world. In the mid-2011 family and I moved from Bangalore, India to Toronto, Canada, where I started my undergraduate degree in Computer Science at York University. As a student, I couldn't wait to get some industry experience, and I was fortunate to land my first job in IT at the University Information Technology department. I started as a Technical Analyst and slowly grew to be a software developer at the Student Information System. Gaining some industry experience gave me the confidence to go and attend a few hackathons across North America. I was fortunate to win a few awards from companies like Google, IBM, Bank of Nova Scotia and more while attending hackathons. With the help of my awards, experience and my skills, I started my internship at SAP Labs in Waterloo, Canada. My course was great, but I was seeking something more challenging, so my hackathon team members and I decided to start a fast-growing development shop Hyfer Technologies. At Hyfer Technologies, I stumbled upon Product Management and Business Analysis while managing a team of developers remotely. So far, I have been able to work with 10+ clients from conception to production. As a product manager, I have had a few failed projects but also some that are still growing strong. As of March 2020, I am working with The Ottawa Hospital as a Business Analyst. As a Product Manager &amp; Business Analyst, my skills include but are not limited to: Management Strategy Growth Strategy Customer, partner and client relations, Organizational Design Process Improvements Statistical Analysis and Data Mining Marketing and Brand Strategy Running Product-Related Sessions Managing technical team Through these skills and experience, I am confident I can add a lot of values to any growing team. I am always open to learning more about you and your business. Feel free to reach out to me or follow me on LinkedIn.

Updated on September 18, 2022

Comments

  • gkmohit
    gkmohit almost 2 years

    Let's say I have a variable

    line="This is where we select from a table."
    

    now I want to grep how many times does select occur in the sentence.

    grep -ci "select" $line
    

    I tried that, but it did not work. I also tried

    grep -ci "select" "$line"
    

    It still doesn't work. I get the following error.

    grep: This is where we select from a table.: No such file or directory
    
    • Marek Zakrzewski
      Marek Zakrzewski over 9 years
      You need to use herestring ...<<<"$line" . The command grep is expecting a file instead
    • Ciro Santilli Путлер Капут 六四事
      Ciro Santilli Путлер Капут 六四事 about 7 years
  • Marco
    Marco over 9 years
    Since the OP wants to count the number of occurrences of a string you can add a wc to complete the task: grep -o <string> <<< "$variable" | wc -l
  • yorkshiredev
    yorkshiredev over 9 years
    +1: Faster, indeed. Works in bash and dash/sh (and probably a few others).
  • Izkata
    Izkata over 9 years
    Use echo "$line" to preserve existing newlines instead of creating ones with tr
  • mikeserv
    mikeserv over 9 years
    @JohnWHSmith - the edit is better, but still just as portable.
  • Michael A
    Michael A over 8 years
    What is the availability of a Here String? Does it require Bash or another shell?
  • Aubergine
    Aubergine about 4 years
    i don't understand how bash question indexing is so bad, answers do not answer the question, how to do: myoutput | grep -v $SOMEVAR condition itself is a variable.
  • Amit Naidu
    Amit Naidu about 4 years
    @Aubergine: copy-pastable examples - Filter-string is a variable: seq 4 | grep -v $SHLVL ; Filter-string from a different process: seq 4 | grep -v "$(seq 2)" Or seq 4 | grep -vf <(seq 2) ; Input from a different process: grep -v $SHLVL <(seq 4) Or grep -v $SHLVL <<< "$(seq 4)"
  • Admin
    Admin almost 2 years
    This looks a lot like John WH Smith’s answer. OK, you’ve added grep -w, but you haven’t explained what that does.
  • Admin
    Admin almost 2 years
    The difference between my answer an Mr. Smith's is that the OP asked for how many matches in a sentence/string, and, to the best of my knowledge, the method using grep (as the OP requested) does not break the sentence into individual lines so that grep can go through it (which is why I used sed). Then wc -l was added to count the number of lines after the regex "select" was matched. The -w on grep makes it only match whole-word results, so something like "selection" won't trigger the filter
  • Admin
    Admin almost 2 years
    Sorry, upon re-reading, I didn't see the 'tr' command with grep initially. So the only difference in my answer and Mr. Smith's is the use of sed
  • Admin
    Admin almost 2 years
    There's too many 'e's in argument (twice)
  • Admin
    Admin almost 2 years
    Fixed, thanks Greenonline!