Regex to replace all spaces in the code block marker of markdown file

Viewed 161

I want to replace each group of spaces with a single comma in code block marker in every markdown file.

For example I have this code block:

```html   class1 class2

Note that above line have two group of spaces, one with 3 spaces, other with single space.

I want to replace it to:

```html,class1,class2

I have tried following command without success:

find src -type f -name "*.md" -exec sed -i s/^(?<=```)( )+/,/g {} +

Meaning: if a line contains ``` at the start then replace all spaces with comma.
But it doesn't work.

What is correct command should I use here?

3 Answers

This will do it (with GNU sed):

sed '/^```/ s/\s\+/,/g' your_file

The ways it's working is as follows:

  • For lines beginning with three backticks... /^```/
  • Replace all (g means global replacement) occurrences of one or more spaces (\s means space, \+ means one or more) with a comma

Once you've confirmed it does what you want, just add the -i to do the substitution in-place:

sed -i '/^```/ s/\s\+/,/g' your_file

You can use

sed -E '/^```/ s/[[:space:]]+/,/g' file

See an online demo

Details:

  • -E enables the POSIX ERE syntax
  • /^```/ - if the line starts with ``` go on and execute the subsequent commands
  • s/[[:space:]]+/,/g - replaces one or more whitespaces with a single , char.
s='```html   class1 class2
html   class3 class4'
sed -E '/^```/ s/[[:space:]]+/,/g' <<< "$s"

Output:

```html,class1,class2
html   class3 class4

Using any awk in any shell on every Unix box:

$ awk -v OFS=',' '/^```/{$1=$1} 1' file
```html,class1,class2

If you want to do "inplace" editing (like you're doing with GNU sed for sed -i) then use GNU awk and make it awk -i inplace -v OFS=',' '/^```/{$1=$1} 1' file

Related