Reputation: 31
I'm trying to loop an awk command using bash script and I'm having a hard time including a variable within the single quotes for the awk command. I'm thinking I should be doing this completely in awk, but I feel more comfortable with bash right now.
#!/bin/bash
index="1"
while [ $index -le 13 ]
do
awk "'"/^$index/ {print}"'" text.txt
done
Upvotes: 1
Views: 1957
Reputation: 21965
awk '/'"$index"'/' text.txt
# A lil play with the script part where you split the awk command
# and sandwich the bash variable in between using double quotes
# Note awk prints by default, so idiomatic awk omits the '{print}' too.
should do, alternatively use grep
like
grep "$index" text.txt # Mind the double quotes
Note : -le
is used for comparing numerals, so you may change index="1"
to index=1
.
Upvotes: 0
Reputation: 42017
Use the standard approach -- -v
option of awk
to set/pass the variable:
awk -v idx="$index" '$0 ~ "^"idx' text.txt
Here i have set the variable idx
as having the value of shell variable $index
. Inside awk
, i have simply used idx
as an awk
variable.
$0 ~ "^"idx
matches if the record starts with (^
) whatever the variable idx
contains; if so, print the record.
Upvotes: 1