Why is this `sed` command not working on my Mac?

0
6
Asked By CuriousCoder42 On

I'm trying to use a `sed` command to replace all runs of whitespace with a dash in a string, but it doesn't seem to work on my Mac. Here's the command I'm using:

```bash
echo "Udemy - The AI Engineer Course 2025 Complete AI Engineer Bootcamp (8.2025)" | sed -E 's/s+/-/g'
```

The output I get is:

```
Udemy - The AI Engineer Cour-e 2025 Complete AI Engineer Bootcamp (8.2025)
```

What's going wrong here?

2 Answers

Answered By UnixGuru77 On

Also, keep in mind that some `sed` implementations treat `s` as a literal 's'. To make your script more portable across Unix systems, you might want to avoid using `-E` with extended regex. Instead, you can use a command like this:

```bash
echo "Udemy - The AI Engineer Course 2025 Complete AI Engineer Bootcamp (8.2025)" | sed 's/[[:space:]]+/-/g; s/--/-/g'
```
This command does two substitutions: first replacing whitespace with dashes, then collapsing multiple dashes into a single dash. This should give you the expected output!

PlanForAllPlatforms -

Very helpful! So it seems like there's no simple way to write a universal script for `sed` across different systems without a bit of tweaking, huh?

Answered By TechieTommy On

It looks like the issue here is related to how your Mac handles `sed`. MacOS uses the BSD version of `sed`, which has different regex syntax compared to GNU `sed`. The `s` you’re using isn’t recognized correctly; instead, you should try using `[[:space:]]` for matching whitespace. So your command would be:

```bash
echo "Udemy - The AI Engineer Course 2025 Complete AI Engineer Bootcamp (8.2025)" | sed -E 's/[[:space:]]+/-/g'
```
This should work without any issues! Let me know if you need more help with that.

StudentSally -

Thanks for the tip! I appreciate the details about BSD vs GNU. I was stuck for a while!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.