Bash script - Grep

Hi,

I am very new to bash scripting and I need to write a bash script that takes two arguments, a string and a file. The output should be each line which matches the string from the beginning of the line. For example, given a string "ANA" the line starting with "ANABEL" will be printed, but the line starting with "SUSANA" will not. I need to use grep.

what I have tried is as follows:

 
#!/bin/bash
grep $1 $2

But this doesn't work, any help or direction will be very help, thanks in advance.

You should use it this way

grep ^$1 $2

^$1 indicated to search at the beginning of the line

regards,
Ahamed

Thanks, but this doesn't work without using echo command inside the script file and I don't know how to make it work.

Can you show us the code (with echo)?

Yes, here is what I have tried inside the script file but it does not work:

thanks.

Something like this

echo "move" important.data | while read pattern filename
pipe while> do
pipe while> grep "^$pattern" $filename
pipe while> done

Try this

a=`grep ^$2 $1`        #assuming, $1 is the file and $2 is the search pattern
echo $a

regards,
Ahamed

I tried this but I still get no correct output...

 
a=`grep ^$2 $1` 
echo $a

so I tried the following way but the results are displayed in one line, if I have a file with multiple lines, I want each line to be echo separately.

 
echo `grep ^$2 $1`

I am now confused with your requirement.
If you want the results in separate line, just do the following in your script

grep ^$2 $1   #this will print the matching lines in separate lines

do you want to do any processing with these lines?

regards,
Ahamed

1 Like

Hey, I don't know why your code didn't work the first time..But it is working now.
Thanks for your help.