5

I can't figure this out. I need to look at every line in file and check out whether it is matching word which is given in variable

I started through command read, but I don't know what am I supposed to use after that, I tried grep but I probably used it wrongly.

while read line; do 
if [ $condition  ] ;then echo "ok" fi
done<file.txt
6

Here's a quickie for you, simply what we're doing is

Line 1: While reading file into variable line

Line 2: Match a regex, echo the $line if matching the word "bird" echo that line. Do whatever actions you need here, in this if statement.

Line 3: End of while loop, which pipes in the file foo.text

#!/bin/bash
while read line; do
  if [[ $line =~ bird ]] ; then echo $line; fi
done <foo.text

Note that "bird" is a regex. So that you could replace it with for example: bird.*word to match the same line with a regular expression.

Try it with a file like so, called foo.text with the contents:

my dog is brown
her cat is white
the bird is the word
  • What exactly means ^$ ? I undetstand that it is some kind of regex, but when I replace it with my own word and own txt file it doesn't work – applenic Mar 17 '15 at 20:36
  • ^anything$ means "match the beginning and end of line", ^ is beginning, and $ means end. so that the whole line is "anything". If you want a partial match like you have a line that says "my dog is brown" and you just want to match dog, get rid of the ^ and $, and just have "dog" there. (edited code to reflect a simplification in regex) – dougBTV Mar 17 '15 at 20:57
5

The easier way to do this, is using grep (or egrep).

grep bird file.txt
0

Here's a simple script that passes in two arguments (filename and variable)... There's also a hardcoded version beneath that.

#!/bin/bash

[ $# -lt 2 ] && echo "wrong number of args" && exit 1
file=$1
var=$2
while read line; do
    if  echo "$line" | grep -q "$var"; then echo "ok"; fi
done < "$file"
exit 0

[user@myserver ~]$ myscript file.txt some_text

Alternatively, if you prefer to hardcode the file (and variable) rather than passing in as an arguments...

while read line; do
    if  echo "$line" | grep -q "some_text"; then echo "ok"; fi
done < file.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.