BASH: How do I grep on a variable?

  • Thread starter Thread starter Zurtex
  • Start date Start date
  • Tags Tags
    Variable
Click For Summary
SUMMARY

The discussion focuses on optimizing the use of the grep command in BASH to search for terms within a CSV file without creating temporary files. Users initially attempted to store the contents of 'books.csv' in a variable and then grep from that variable, which resulted in errors due to incorrect file handling. The recommended solutions include directly referencing the CSV file with 'bookfile=books.csv' and using 'printf' to pipe the contents of the variable into grep, effectively avoiding the pitfalls of file expansion.

PREREQUISITES
  • Understanding of BASH scripting
  • Familiarity with the grep command
  • Knowledge of file handling in Linux
  • Basic command-line operations
NEXT STEPS
  • Learn advanced BASH scripting techniques
  • Explore the use of pipes and redirection in BASH
  • Investigate the performance implications of using temporary files
  • Study the 'find' command for searching files in directories
USEFUL FOR

BASH developers, system administrators, and anyone looking to optimize file searching and processing in Linux environments.

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
 

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