1

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
1
  • 2
    Why not just grep "^$index" ? Seems like using awk for this purpose is over the top... Commented Jun 22, 2017 at 4:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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.

1 Comment

'/'"$index"'/' this is bad practice, use -v varname="somevalue" instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.