插入在bash字符串的新线的最简单方法

问题描述 投票:1回答:1

我有一个bash的字符串,如下所示:

string="This is the first line.
This is the second line"

我想这个转换成一个Git提交信息,所以我需要插入一个空行的第一行后,使其提交的标题,第二行提交身体,使扩张看起来是这样的:

This is the first line.

This is the second line

什么是在bash实现这一目标的最简单的方法?

bash
1个回答
4
投票

这应该做(它取代由两个连续的换行符找到的第一个换行符):

string="This is the first line.
This is the second line"
new_string=${string/$'\n'/$'\n\n'}
echo "$new_string"

所述${var/pattern/replacement}Parameter Expansion;它扩展到var的第一次出现是由pattern取代replacement的扩张。

所述$'...'称为ANSI-C quoting并且将允许转义序列。

© www.soinside.com 2019 - 2024. All rights reserved.