midori
midori

Reputation: 4837

How to substitue a pattern with a whole array using sed?

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

Answers (2)

izabera
izabera

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

  • set IFS=, (Internal Field Separator)
  • convert all the elements of your array to a single string with ${langs[*]}
  • prepend a space before each one of them by replacing the beginning of each string (# in bash, like ^ in regex) with a space

The 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

John1024
John1024

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.

Example

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

Related Questions