在 bash 中用 <br /> 替换 \n
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45145353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace \n with <br /> in bash
提问by WalterBeiter
[UPDATED QUESTION]
[更新的问题]
I've got a variable $CHANGED
which stores the output of a subversion command like this: CHANGED="$(svnlook changed -r $REV $REPOS)"
.
我有一个变量$CHANGED
存储这样的颠覆命令的输出:CHANGED="$(svnlook changed -r $REV $REPOS)"
。
Executing svnlook changed -r $REV $REPOS
will output the following to the command line:
执行svnlook changed -r $REV $REPOS
将输出以下内容到命令行:
A /path/to/file
A /path/to/file2
A /path/to/file3
However, I need to store the output formatted as shown below in a variable $FILES
:
但是,我需要将格式如下所示的输出存储在变量中$FILES
:
A /path/to/file<br />A /path/to/file2<br />A /path/to/file3<br />
I need this for using $FILES
in a command which generates an email massage like this:
我需要$FILES
在一个命令中使用它来生成这样的电子邮件消息:
sendemail [some-options] $FILES
It should to replace $FILES
with A /path/to/file<br />A /path/to/file2<br />A /path/to/file3<br />
so that it can interpret the html break tags.
它应该替换为$FILES
,A /path/to/file<br />A /path/to/file2<br />A /path/to/file3<br />
以便它可以解释 html 中断标记。
回答by hek2mgl
回答by Jahid
You can modify hek2mgl's answerto strip out the first <br />
(if any):
您可以修改hek2mgl 的答案以去除第一个<br />
(如果有):
CHANGED="
A /path/to/file
A /path/to/other/file
A /path/to/new/file
"
FILES="$(echo "${CHANGED//$'\n'/<br />}" | sed 's#^<br />##g')"
echo "$FILES"
Output:
输出:
A /path/to/file<br />A /path/to/other/file<br />A /path/to/new/file<br />
另一种方式(只有
sed
sed
):FILES="$(echo "$CHANGED" | sed ':a;N;$!ba;s#\n#<br />#g;s#^<br />##g')"
回答by Toby Speight
The Parameter Expansionsection of the man page is your friend.
手册页的参数扩展部分是您的朋友。
Starting with
从...开始
changed="
A /path/to/file
A /path/to/other/file
A /path/to/new/file
"
You can remove leading and trailing newlines using the #
and %
expansions:
您可以使用#
和%
扩展删除前导和尾随换行符:
files="${changed#$'\n'}"
files="${files%$'\n'}"
Then replace the other newlines with <br />
:
然后将其他换行符替换为<br />
:
files="${files//$'\n'/<br />}"
Demonstration:
示范:
printf '***%s***\n' "$files"
***A /path/to/file<br />A /path/to/other/file<br />A /path/to/new/file***
(Note that I've changed your all-uppercase variable names to lower case. Avoid uppercase names for your locals, as these tend to be used for communication via the environment.)
(请注意,我已将您的全大写变量名称更改为小写。避免对本地人使用大写名称,因为这些名称往往用于通过环境进行通信。)
If you dislike writing newline as $'\n'
, you may of course store it in a variable:
如果您不喜欢将换行符写为$'\n'
,您当然可以将其存储在一个变量中:
nl=$'\n'
files="${changed#$nl}"
files="${files%$nl}"
files="${files//$nl/<br />}"