regex - How to substitue a pattern with a whole array using sed? -
i have array, looks this:
snakes=(python boa cornsnake milksnake) i wondering if it's possible substitute pattern whole array using sed. thinking this:
sed -i "s/snakes like/& $(echo ${snakes[@]})/g" snakes.txt and have output here separated , :
snakes python, boa, cornsnake, milksnake any ideas or suggestions appreciated.
you expanding array correctly.
suppose want edit file called languages (snakes gross):
$ cat languages languages like. and array this:
$ langs=(python perl ruby lua) you have to
- set
ifs=,(internal field separator) - convert elements of array single string
${langs[*]} - prepend space before each 1 of them replacing beginning of each string (
#in bash,^in regex) space
the final command one:
$ ifs=, ; sed -i "s|languages like|&${langs[*]/#/ }|" languages (i used | in sed command clarity, / fine too, since shell converting ${langs[*]/#/ } final string before passing sed)
the languages file looks this:
i languages python, perl, ruby, lua.
Comments
Post a Comment