Reputation: 1
I am trying figure out how I can ask a user for input, use the input as the pattern to match with grep, and return the line number to a variable.
echo "What BCP do you want?"
read BCPid # Get what value we're interested in.
for i in *.txt
do
BCPlinenum=$(echo "$BCPid" | (grep -n "$BCPid" |cut -f1 -d:))
echo "$BCPlinenum"
done
This returns a value of 1, regardless of what I input.
The file it searches looks as follows,
BCP C1 C2
BCP C1 C3
BCP C1 C4
BCP C2 C3
BCP C2 C4
BCP C3 C4
So, the desired function is to input "BCP C1 C2" and have it return 1 (the line number) to a variable.
Thank you!
Upvotes: 0
Views: 94
Reputation: 4340
here it is, no loop required:
echo "What BCP do you want?"
read BCPid # Get what value we're interested in.
results=`grep -nH "$BCPid" *.txt | cut -f1,2 -d:`
you can use a loop (or something better) to handle the output:
grep -nH "$BCPid" *.txt | cut -f1,2 -d: |
while IFS=: read file n; do
echo "found match in file $file on line $n"
done
Upvotes: 0
Reputation: 295291
You aren't actually feeding your input file into grep
.
Change
BCPlinenum=$(echo "$BCPid" | (grep -n "$BCPid" |cut -f1 -d:))
to
BCPlinenum=$(grep -n -e "$BCPid" <"$i" | cut -f1 -d:)
or
BCPlinenum=$(grep -n -e "$BCPid" -- "$i" | cut -f1 -d:)
Upvotes: 2