Question

I have the following Markdown file:

# Headline 1 #

Some text

## Subheadline 1 ##

More text

# Headline 2 #

Even more text

and I'd like to deepen the headline level into:

## Headline 1 ##

Some text

### Subheadline 1 ###

More text

## Headline 2 ##

Even more text

I'm talking about 300 pages of text so doing it manually would be a PITA. I'm happy with a vim, sed, bash, Sublime and Atom solution to that "simple" problem.

What is the best way to solve this problem?

Was it helpful?

Solution

Sublime Text has regex search and replace feature. Just press Ctrl+h and search for (#+)([^#]+)(#+) and replace with #$1$2#$3.

enter image description here

This pattern would only match lines that are heading and leave out any other # character you have in your file.

OTHER TIPS

In vim I would go with something like this:

%s/^\(#.*#\)/#\1#/g

This might work for you (GNU sed):

sed -i 's/# [^#]* #/#&#/g' file

This is a solution for vim. First you need to start vim giving as args the list of files you want to work on (I suppose here we are talking about all Markdown files in a directory)

If your shell is zsh

$ vim **/*.md

Otherwise

$ vim `find . -type f -name *.md`

Then, inside vim do

:argdo %s/^#\|#$/##/ge | update

This will replace the starting and the ending '#' with a double '##' in all your files in one single command. This will work also for headers that don't have the trailing '#'. The 'g' flag is needed for the headers that have both leading and trailing '#'. The 'e' flag tells vim that it's not an error to be unable to find the pattern in a file. The final 'update' saves the file only if it's changed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top