BASH: How do I grep on a variable?

  • Thread starter Zurtex
  • Start date
  • #1
Zurtex
Science Advisor
Homework Helper
1,120
1

Main Question or Discussion Point

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

Code:
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:
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?
 

Answers and Replies

  • #2
365
0
bookfile=$(cat books.csv)
would expand to the contents of the file, which when executed with
grep -i horror $bookfile
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:
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:
bookfiles=`ls *.csv`
grep -i horror $bookfiles
 
  • #3
Zurtex
Science Advisor
Homework Helper
1,120
1
Oh that's cool, I'll try it out :smile:

I also got another solution:

Code:
bookfile=$(cat books.csv)
printf "%s\n" "$bookfile" | grep -i horror
 

Related Threads for: BASH: How do I grep on a variable?

Replies
1
Views
1K
Replies
2
Views
3K
Replies
4
Views
2K
  • Last Post
Replies
1
Views
8K
Replies
5
Views
2K
  • Last Post
Replies
10
Views
12K
Replies
9
Views
1K
Top