Home > Blockchain >  Bash: replace spaces with new line and prepend with dash
Bash: replace spaces with new line and prepend with dash

Time:07-17

I'm trying to replace a space-separated string of categories with the categories on new lines prepended with a dash

I've got as far as to replace new lines with a dash

categories="cat1 cat2 cat3 cat4 cat5"

mod_categories="$(echo -e "$categories" | sed 's/ /\n- /g')"

echo $mod_categories

which outputs

cat1
- cat2
- cat3
- cat4
- cat5

The desired output however would be where cat1 also includes a prepended dash:

- cat1
- cat2
- cat3
- cat4
- cat5

Thanks for reading/helping

CodePudding user response:

I suggest to use an array and printf:

categories=(cat1 cat2 cat3 cat4 cat5)
printf -- "- %s\n" "${categories[@]}"

Output:

- cat1
- cat2
- cat3
- cat4
- cat5

CodePudding user response:

With bash parameter expansion and ANSI-C quoting

echo "- ${categories// /$'\n- '}"

CodePudding user response:

You can replace the start of the first line with a hyphen and space using

mod_categories="$(echo -e "$categories" | sed 's/ /\n- /g;1s/^/- /')"

See the online demo:

#!/bin/bash
categories="cat1 cat2 cat3 cat4 cat5"
mod_categories="$(echo -e "$categories" | sed 's/ /\n- /g;1s/^/- /')"
echo "$mod_categories"

Output:

- cat1
- cat2
- cat3
- cat4
- cat5
  • Related