BASH: How do I grep on a variable?

  1. Zurtex

    Zurtex 1,123
    Science Advisor
    Homework Helper

    Hi, I've been running code which very frequently calls books.csv. e.g:

    Code (Text):

    grep -i horror books.csv > temp
    Except, I'm trying to move away from using temporary files or frequently calling books.csv to improve efficiency. So I tried something like

    Code (Text):

    bookfile=$(cat books.csv)
    grep -i horror $bookfile
    Needless to say, it explodes (giving me about 40 lines of grep [data here] no such file or director), that's before I even try and save my grep output as a variable. Don't suppose anyone knows what path I need to be taking?
     
  2. jcsd
  3. would expand to the contents of the file, which when executed with
    will try to grep from files represented by the content of the csv file, in which case most probably the files don't exist.

    If you want to use a parameter to represent the csv file, you could try:
    Code (Text):

    bookfile=books.csv
    grep -i horror $bookfile
     
    or better still, if you want to grep from all .csv files (if you have many of them)
    Code (Text):

    bookfiles=`ls *.csv`
    grep -i horror $bookfiles
     
     
  4. Zurtex

    Zurtex 1,123
    Science Advisor
    Homework Helper

    Oh that's cool, I'll try it out :smile:

    I also got another solution:

    Code (Text):

    bookfile=$(cat books.csv)
    printf "%s\n" "$bookfile" | grep -i horror
     
     
Know someone interested in this topic? Share a link to this question via email, Google+, Twitter, or Facebook