Home > Software engineering >  Bash: Store sed result into array?
Bash: Store sed result into array?

Time:11-19

How to fix the following code so that it can store the result of sed, which will replace the _
with -?

My code:

names=()
for entry_ in $foo
do
  names =($entry_ | sed -e "s/_/-/g")
done

echo names

CodePudding user response:

You don't need sed for this, you can use bash's built-in parameter expansion substitution capability to replace all _ characters with -: ${var//_/-}. You can even use it to do this for the entire list of elements in a single operation, but how you do it depends on what the source variable, foo, actually is.

If foo is an array (the much better way to do things), you can combine [@] ("get me all elements of the array") with the substitution:

names=( "${foo[@]//_/-}" )

If foo is a plain string, and you need to use word splitting to break it into elements for the array, you can do essentially the same thing without the [@] ('cause it's not an array) or the double-quotes (which prevent word splitting):

names=( ${foo//_/-} )

Note: I recommend avoiding word splitting if possible -- it often does something close to what you want, but almost never exactly what you want.

P.s. I third the recommendation of shellcheck. Among other things, it'll flag anything involving word splitting as a probable mistake.

CodePudding user response:

This should be enough to get you there.

names=()

names =$(echo "hello_world" | sed -e "s/_/-/g")

echo $names

Note that you need $ before echoing your variable.

Also. Look into installing shellcheck for your code editor and it will help you catch sneaky bugs and build better shell programming practices.

  • Related