Scott Porad
Scott Porad

Reputation: 293

How to replace some spaces with hyphens using sed?

I'm doing some wiki/markdown transformations, and have string like this:

[[Moo Cow]]

and I want it to be like this:

[Moo Cow](Moo-Cow.html)

How can I do this using sed?

Upvotes: 2

Views: 176

Answers (3)

Scott Porad
Scott Porad

Reputation: 293

This is a sed command that will do that for you:

sed -i 's/\]\]/\]\(\.html\)/g; s/\[\[/\[/g; s/\[\(.*\)\](\.html)/\[\1\](\1.html)/g; :a;s/\(([^)]*\) /\1-/;ta' filename.md

No, that is not pretty. Yes, that is ugly. But, it works.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203368

Just use awk:

$ awk '{gsub(/[][]/,""); x=$0; gsub(/ /,"-"); printf "[%s](%s).html\n", x, $0}' file
[Moo Cow](Moo-Cow).html

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can reduce your sed expression like this:

sed -i 's/\[\[\([^]]*\)]]/[\1](\1.html)/g;:a;s/\(]([^) ]*\) /\1-/g;ta;' file

or with perl:

perl -pe's/\[\[([^]]*)]]/$a=$1;$a=~y# #-#;"[$1]($a.html)"/ge' file

Upvotes: 2

Related Questions