2

This works fine since because i'm directly inputting the data.

declare -a arr
arr=( $(awk '/123456789/{print NR}' filename) )
echo ${arr[0]}
echo ${arr[*]}

Bt when i do as below, it doesn't work. Can u let me know how the parameter 'name' can be used in the command below :

echo  Enter your search string:  
read name
declare -a arr
arr=( $(awk '/"$name"/{print NR}' filename )
echo ${arr[0]}
echo ${arr[*]}

2 Answers 2

2

Based on your comments I am posting this answer. This is the script that will work for you:

read -e -p "Enter your search string: " name
#echo "name: [$name]"
declare -a arr
arr=( $(awk /"$name"'/{print NR}' x ) )
echo ${arr[0]}
echo ${arr[*]}
Sign up to request clarification or add additional context in comments.

8 Comments

@ Anubhava : Thank U. Your comments and modifications in the script are very helpful But what's wrong in the above script ?
@JackieJames: Sorry to respond late, I think you've figured it out that your script had one missing right parenthesis ) in awk command.
@ Anubhava : No, not paranthesis it's misplace of single quote. arr=( $(awk /"$name"'/{print NR}' x ) ) correct arr=( $(awk /"$name"/'{print NR}' filename ) misplace of single quote
@ Anubhava : Can you please look into this 'Is it possible to write the below code in shell script?' This is another different post.
@ Anubhava : Can u please check the post by title "Is it possible to write the below code in shell script?"
|
1
arr=( $(awk /"$name"/'{print NR}' filename ) )

3 Comments

echo enter the string to be searched : read name declare -a arr arr=( $(awk /"$name"/'{print NR}' filename ) echo ${arr[0]} echo ${arr[*]} Output : enter the string to be searched : 123456789 ./newarray.sh: line 4: unexpected EOF while looking for matching `)'
@ Jens : Your command is right but there is a misplace of single quote. arr=( $(awk /"$name"'/{print NR}' filename ) ) Thank U, Anubhava :)
No, there's no misplacement. There are no spaces around the / so the shell parses /"$name"/'{print NR}' as one token.

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.