Reputation: 11138
I have a bash string that looks like this:
string="This is the first line.
This is the second line"
I would like to convert this into a git commit message, so I need to insert a blank line after the first line to make it the commit title, and the second line the commit body, so that the expansion looks like this:
This is the first line.
This is the second line
What is the simplest way to achieve this in bash?
Upvotes: 1
Views: 59
Reputation: 46903
This should do (it replaces the first newline character found by two consecutive newline characters):
string="This is the first line.
This is the second line"
new_string=${string/$'\n'/$'\n\n'}
echo "$new_string"
The ${var/pattern/replacement}
is a Parameter Expansion; it expands to the expansion of var
where the first occurrence of pattern
is replaced by replacement
.
The $'...'
is known as ANSI-C quoting and will allow escape sequences.
Upvotes: 4