简体   繁体   中英

Replace \n with <br /> in bash

[UPDATED QUESTION]

I've got a variable $CHANGED which stores the output of a subversion command like this: CHANGED="$(svnlook changed -r $REV $REPOS)" .

Executing svnlook changed -r $REV $REPOS will output the following to the command line:

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 :

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:

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.

In bash:

echo "${VAR//$'\n'/<br />}"

See Parameter Expansion

You can modify hek2mgl's answer to strip out the first <br /> (if any):

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 />


Another way (with only sed ):

 FILES="$(echo "$CHANGED" | sed ':a;N;$!ba;s#\\n#<br />#g;s#^<br />##g')" 

The Parameter Expansion section 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 /> :

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:

nl=$'\n'
files="${changed#$nl}"
files="${files%$nl}"
files="${files//$nl/<br />}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM