Register to reply

BASH: How do I grep on a variable?

by Zurtex
Tags: bash, grep, variable
Share this thread:
Zurtex
#1
Apr22-09, 04:02 PM
Sci Advisor
HW Helper
P: 1,123
Hi, I've been running code which very frequently calls books.csv. e.g:

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

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?
Phys.Org News Partner Science news on Phys.org
Scientists develop 'electronic nose' for rapid detection of C. diff infection
Why plants in the office make us more productive
Tesla Motors dealing as states play factory poker
mathmate
#2
Apr23-09, 09:26 PM
P: 366
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:
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)
bookfiles=`ls *.csv`
grep -i horror $bookfiles
Zurtex
#3
Apr24-09, 01:03 AM
Sci Advisor
HW Helper
P: 1,123
Oh that's cool, I'll try it out

I also got another solution:

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


Register to reply

Related Discussions
BASH Script to Rename Multiple Files Programming & Computer Science 2
Two hour SNL Presidential bash tonight General Discussion 21
Filenames with spaces in Bash script Programming & Computer Science 1
AMD wins big at intel bash. General Discussion 0
No Bash Computing & Technology 0