2

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

koahv
  • 59
  • 5
  • 1
    `echo $mod_categories` doesn't give the output you state -- it needs to be `echo "$mod_categories"` _with the quotes_ to preserve newlines, unless you've modified IFS. See [I just assigned a variable but `echo $variable` shows something else](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Jul 17 '22 at 12:40
  • 2
    BTW, the [unix.se] question [Why is printf better than echo?](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo) has an excellent answer that also describes why `echo -e` is unreliable (strictly POSIX-compliant shells don't honor it as an option but instead treat `-e` as something to print, and depending on bash's runtime settings, sometimes it's compliant in that way too). – Charles Duffy Jul 17 '22 at 12:42

3 Answers3

7

I suggest to use an array and printf:

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

Output:

- cat1
- cat2
- cat3
- cat4
- cat5
Cyrus
  • 84,225
  • 14
  • 89
  • 153
5

With bash parameter expansion and ANSI-C quoting

echo "- ${categories// /$'\n- '}"
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

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

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

See the online demo:

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

Output:

- cat1
- cat2
- cat3
- cat4
- cat5
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563