Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash search for string in each line of file

I'm trying what seems like a very simple task: use bash to search a file for strings, and if they exist, output those to another file. It could be jetlag, but this should work:

#!/bin/bash

cnty=CNTRY

for line in $(cat wheatvrice.csv); do
    if [[ $line = *$cnty* ]]
    then
        echo $line >> wr_imp.csv
    fi
done

I also tried this for completeness:

#!/bin/bash

cnty=CNTRY

for line in $(cat wheatvrice.csv); do
    case $line in 
    *"$cnty"*) echo $line >> wr_imp.csv;;
    *) echo "no";;
    esac
done

both output everything, regardless of whether the line contains CNTRY or not, and I'm copy/pasting from seemingly reliable sources, so apparently there's something simple about bash-ness that I'm missing?

like image 940
Joshua Noble Avatar asked Apr 17 '11 19:04

Joshua Noble


2 Answers

Don't use bash, use grep.

grep -F "$cnty" wheatvrice.csv >> wr_imp.csv
like image 64
Ignacio Vazquez-Abrams Avatar answered Oct 15 '22 19:10

Ignacio Vazquez-Abrams


While I would suggest to simply use grep too, the question is open, why you approach didn't work. Here a self referential modification of your second approach - with keyword 'bash' to match itself:

#!/bin/bash

cnty=bash    
while read -r line
do
    case $line in 
        *${cnty}*) 
            echo $line " yes" >> bashgrep.log
            ;;
        *)
                echo "no"
                ;;
    esac
done < bashgrep.sh

The keypoint is while read -r line ... < FILE. Your command with cat involves String splitting, so every single word is processed in the loop, not every line.

The same problem in example 1.

like image 30
user unknown Avatar answered Oct 15 '22 21:10

user unknown