Friday, July 29, 2022

[SOLVED] Bash: replace spaces with new line and prepend with dash

Issue

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


Solution

With bash parameter expansion and ANSI-C quoting

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


Answered By - glenn jackman
Answer Checked By - Katrina (WPSolving Volunteer)