Search code examples
shellunixquoting

Storing values in an array using shell scripting


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[*]}

Solution

  • 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[*]}