Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add characters to beginning of every line in a file

I am attempting to create a bash script that prepends characters to the start of all lines in a markdown file which do not begin with a '#' character.

For example, say we have example.md:

# Title
Words
More words

## Title 2
123

I want to add a string (let's say, 'PREFIX') to the beginning of every line except those two title lines.

Relatedly, how would I do this to only lines which begin with a letter?

For clarity, the bash script would look something like this other script I use, trim_duplicate_newlines.sh:

#!/bin/bash
awk 'BEGIN{RS="\n+" ; ORS="\n";}{ print }'

which I would run in the cmd like this: cat ./example.md | ./trim_duplicate_newlines.sh

like image 932
BirdsAreBastards Avatar asked Nov 01 '25 02:11

BirdsAreBastards


2 Answers

This will do

awk '!/^#/ { printf "PREFIX " } { print }' example.md

The regular expression /^#/ matches the title lines, but the exclamation point negates it.

like image 145
Hai Vu Avatar answered Nov 02 '25 16:11

Hai Vu


With GNU sed:

sed '/^#/!s/^/PREFIX/' file.md

Output:

# Title
PREFIXWords
PREFIXMore words
PREFIX
## Title 2
PREFIX123
like image 35
Cyrus Avatar answered Nov 02 '25 16:11

Cyrus



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!