1

i want to print all array data of foo line by line but this loop is printing last line of string of array it is not printing all line of array variable please help.

foo=( $(grep name  emp.txt) ) 
while read -r line ; do echo "$line"
done <<< ${foo[@]}
Cyrus
  • 84,225
  • 14
  • 89
  • 153
Vijay
  • 197
  • 10

1 Answers1

2

While David C. Rankin presented a working alternative, he chose to not explain why the original approach didn't work. See the Bash Reference Manual: Word Splitting:

The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting.

So, you can make your approach work by using double quotes around the command substitution as well as the parameter expansion:

foo=("$(grep name emp.txt)") 
while read -r line; do echo "$line"
done <<<"${foo[@]}"

Note that this assigns the whole grep output to the sole array element ${foo[0]}, i. e., we don't need an array at all and could use a simple variable foo just as well.

If you do want to read the grep output lines into an array with one line per element, then there's the Bash Builtin Command readarray:

< <(grep name emp.txt) readarray foo

This uses the expansion Process Substitution.

i want to replace some text can i use sed command in echo "$line"

Of course you can use echo "$line" | sed ….

Armali
  • 18,255
  • 14
  • 57
  • 171