Reputation: 9885
I have two examples of a bash script. All I do is just use sed
to replace some strings in a file. The file is specified when the script is run. So, you would run it like ./replace_file.sh input_file
.
hug="g h 7"
for elm in $hug
do
echo "replacing $elm"
sed -i'_backup' "s/$elm/BOO/g" $1
done
and
hug=('g' 'h' '7')
for elm in $hug
do
echo "replacing $elm"
sed -i'_backup' "s/$elm/BOO/g" $1
done
The first script above, echos the following:
replacing g
replacing h
replacing 7
But, the second one stops after replace g
. It is unclear to me why. Can someone please shed some light?
Thank you.
Upvotes: 0
Views: 98
Reputation: 84642
As set forth in the comment, when you attempt to iterate over the elements in the array by calling for elm in $hug
, you are simply referencing the first element in the array. To iterate over the elements in the array, you use the array syntax, e.g. ${array[@]}
to access each element sequentially (and you can quote the array to preserve whitespace in the elements.) In your case you need only:
#!/bin/bash
hug=('g' 'h' '7')
for elm in ${hug[@]}
do
echo "replacing $elm"
# sed -i'_backup' "s/$elm/BOO/g" $1
done
Output
$ bash arrayiter.sh
replacing g
replacing h
replacing 7
Upvotes: 2