Awk : Trying to count lines with user input
Hello,
I am trying to write a script that will use awk to take an user input field and check and count the lines that contain the entry: ie: ./test.sh search_text file Code: num=$(awk '/$1/ {++x} END {print x+0}' $2) if [ $num -eq 0 ]; then echo $num" organisms named "$1" found! Try changing syntax or organism does not exist." else awk '/$1/ {print $0}' $2 > $1.txt echo "The number of organisms found is" $num"! A new file named "$1".txt has been created!" fi If I change $1 to what I am actually looking for it works :) Any ideas? Thank so much! |
How about just:
Code:
grep -c search_text file |
Quote:
1. Why use bash at all? Just write the whole script in awk. You simply change your interpreter: Code:
#!/bin/bash 2. Both bash and awk have a $1 variable and they are not related 3. Placing a field inside the regex will never work :- /$1/ ... remember that $ has a special meaning and no escaping it will not help. 4. 'print x+0' .... why?? what was wrong with 'print x'? 'x' is not a string |
Thanks for the suggestions. I am still very new at this!
I like the grep command. But we are just learning about bash so our script has to use awk. I was fooling around with my code: by adding organism="$1" and changing the line num=$(awk '/$1/ {++x} END {print x+0}' $2) to num=$(awk '/'$organism'/ {++x} END {print x+0}' $2) it works :) Thanks for suggestions and helping me clean up my code! The reason for the x+0 is that if x=0 then it leaves x blank- its strange (even if i attach num=0 at the top of my code) |
Again you need to remember that any variable in bash is not related to any variable in awk (unless you tell it somehow).
Even though you might set num=0, once the awk script runs, if the value of x has not been incremented it will be blank and this is then passed back to num hence the original value of 0 is now gone. The other reason for suggestion to do all in awk is to not then require you to run the same awk query twice. May I suggest you have a look at the '-v' option for awk. Your current solution to alter the quoting works fine in this case but once you start to need more variables translated into the awk script this will become unmanageable. Lastly, you may also wish to look at the BEGIN clause for setting variables. |
All times are GMT -5. The time now is 09:19 AM. |