Reputation: 4837
I have an array, which looks like this:
snakes=(python boa cornsnake milksnake)
I was wondering if it's possible to substitute a pattern with a whole array using sed. I was thinking about something like this:
sed -i "s/snakes like/& $(echo ${snakes[@]})/g" snakes.txt
And have the output here like this separated by ,
:
snakes like python, boa, cornsnake, milksnake
Any ideas or suggestions would be very appreciated.
Upvotes: 0
Views: 1856
Reputation: 669
You could do that by just expanding the array correctly.
Suppose you want to edit a file called languages (snakes are gross):
$ cat languages
I like languages like.
And your array is like this:
$ langs=(python perl ruby lua)
You just have to
IFS=,
(Internal Field Separator)${langs[*]}
#
in bash, like ^
in regex) with a spaceThe final command is simply this one:
$ IFS=, ; sed -i "s|languages like|&${langs[*]/#/ }|" languages
(I used |
in the sed command for clarity, but /
would be fine too, since
your shell is converting ${langs[*]/#/ }
to the final string before passing
it to sed)
The languages file now looks like this:
I like languages like python, perl, ruby, lua.
Upvotes: 3
Reputation: 113864
With this definition for the array:
$ snakes=(python boa cornsnake milksnake)
We need two steps. The first is to create a string s
which will contain the elements of the array snakes
separated by a comma and a space:
$ printf -v s ', %s' "${snakes[@]}"
Then, use s
in the sed
command:
$ sed -i "s/snakes like/& ${s:2}/g" snakes.txt
${s:2}
is used to eliminate the extra comma-space that occurs at the beginning of s
.
Consider this sample file:
$ cat snakes.txt
I like snakes like.
I don't like snakes.
Apply sed
:
$ sed -i "s/snakes like/& ${s:2}/g" snakes.txt
The file now contains:
$ cat snakes.txt
I like snakes like python, boa, cornsnake, milksnake.
I don't like snakes.
Upvotes: 1