Unix bash cutting and grep
You can do this without cut
, and without grep
if you're ok with bash's regular expression matching (or can use shell pattern matching instead).
The idea would be to read the file line by line, then split the line into an array.Once you've got that, do the comparisons and output you want.
Here's a demo of the technique:
#! /bin/bashecho "Title:"read title# shopt -s nocasematch # if you want case-insensitive matchingwhile read line ; do # this read takes data from input.txt, see # end of loop IFS=: read -a parts <<< "$line" # this splits the line on ":" into # an array called parts if [[ ${parts[0]} =~ $title ]] ; then # regex matching printf "%s -- %s\n" "${parts[1]}" "${parts[2]}" fidone < input.txt
The next step up from grep
and cut
is awk
. Unless you must do this using bash
(is this homework?), then awk
would make things considerably easier:
awk -F: '/harry potter/ { sub(/^/,"$",$(NF-2)); print }' IGNORECASE=1 OFS=", " db.txt
Test input:
Harry Potter and the Sorcerer's Stone:J.K. Rowling:21.95:100:200Harry Potter and the Chamber of Secrets:J.K. Rowling:21.95:150:300Lord of the Rings, The Fellowship of the Ring:J.R.R. Tolkien:32.00:500:500A Game of Thrones:George R.R. Martin:44.50:300:250
Test output:
Harry Potter and the Sorcerer's Stone, J.K. Rowling, $21.95, 100, 200Harry Potter and the Chamber of Secrets, J.K. Rowling, $21.95, 150, 300
read -p "Enter title: " TITLEwhile IFS=: read title author price x y; do if [[ ${title,,} == *${TITLE,,}* ]]; then printf "%s, %s, $%s, %s, %s\n" "$title" "$author" "$price" "$x" "$y" fidone < db.txt
The test in the if command does a simple glob-match but case insensitively, so it will match if the user enters "potter".
Or, use sed to change the separators:
read -p "Enter title: " TITLEsed '/'"$TITLE"'/I!d; s/:/, /g' db.txt
which means delete all lines that do not match the TITLE, then transform the separator.