Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: replace spaces with new line and prepend with dash

Tags:

bash

sed

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

like image 585
koahv Avatar asked Mar 03 '26 18:03

koahv


2 Answers

I suggest to use an array and printf:

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

Output:

- cat1
- cat2
- cat3
- cat4
- cat5
like image 167
Cyrus Avatar answered Mar 05 '26 09:03

Cyrus


With bash parameter expansion and ANSI-C quoting

echo "- ${categories// /$'\n- '}"
like image 26
glenn jackman Avatar answered Mar 05 '26 07:03

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!