BASH: How do I grep on a variable?

  • Thread starter Thread starter Zurtex
  • Start date Start date
  • Tags Tags
    Variable
Click For Summary
The discussion revolves around optimizing the process of searching for terms in a CSV file, specifically "books.csv," without relying on temporary files. The initial attempt to store the contents of the CSV in a variable and then grep from it resulted in errors, as the command was misinterpreted to search for files named after the content of the CSV. The correct approach suggested includes directly referencing the file in the grep command, such as using "bookfile=books.csv" or using a wildcard to search through all CSV files. An alternative solution provided involves using printf to pipe the contents of the CSV file into grep, which successfully filters the desired output without creating temporary files.
Zurtex
Science Advisor
Homework Helper
Messages
1,118
Reaction score
1
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?
 
Technology news on Phys.org
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
 
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
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 9 ·
Replies
9
Views
2K
Replies
1
Views
5K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
4
Views
3K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 5 ·
Replies
5
Views
4K
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
Replies
16
Views
3K