简体   繁体   中英

Adding newline characters to unix shell variables

I have a variable in a shell script in which I'd like to format the data. The variable stores new data during every iteration of a loop. Each time the new data is stored, I'd like to insert a new line character. Here is how I'm trying to store the data into the variable.

VARIABLE="$VARIABLE '\n' SomeData"

Unfortunately, the output includes the literal '\n' Any help would be appreciative.

Try $'\\n' :

VAR=a
VAR="$VAR"$'\n'b
echo "$VAR"

gives me

a
b

A common technique is:

nl='
'
VARIABLE="PreviousData"
VARIABLE="$VARIABLE${nl}SomeData"

echo "$VARIABLE"
PreviousData
SomeData

Also common, to prevent inadvertently having your string start with a newline:

VARIABLE="$VARIABLE${VARIABLE:+$nl}SomeData"

(The expression ${VARIABLE:+$nl} will expand to a newline if and only if VARIABLE is set and non-empty.)

VAR="one"
VAR="$VAR.\n.two"
echo -e $VAR

Output:

one.
.two

Other than $'\\n' you can use printf also like this:

VARIABLE="Foo Bar"
VARIABLE=$(printf "${VARIABLE}\nSomeData")
echo "$VARIABLE"

OUTPUT:

Foo Bar
SomeData

I had a problem with all the other solutions: when using a # followed by SPACE (quite common when writing in Markdown) both would get split onto a new line.

So, another way of doing it would involve using single quotes so that the "\\n" get rendered.

FOO=$'# Markdown Title #\n'
BAR=$'Be *brave* and **bold**.'
FOOBAR="$FOO$BAR"

echo "$FOOBAR"

Output:

# Markdown Title #
Be *brave* and **bold**.

Single quote All special characters between these quotes lose their special meaning.
https://www.tutorialspoint.com/unix/unix-quoting-mechanisms.htm

So the syntax you use does something different that you want to achieve.

This is what you need:

The $'\\X' construct makes the -e option in echo unnecessary.
https://linux.die.net/abs-guide/escapingsection.html

echo -e "something\nsomething"

or

echo "something"$'\n'"something"

It's a lot simpler than you think:

VARIABLE="$VARIABLE
SomeData"

Building upon the first two solutions, I'd do like shown below. Concatenating strings with the '+=' operator, somehow looks clearer to me.

Also rememeber to use printf as opposed to echo, you will save yourself so much trouble

sometext="This is the first line"
sometext+=$'\n\n'
sometext+="This is the second line AFTER the inserted new lines"
printf '%s' "${sometext}"

Outputs:

This is the first line

This is the third line AFTER the inserted new line

Your problem is in the echo command, in ash you have to use the option -e to expand special characters. This should work for you:

VAR="First line"
VAR="$VAR\nSecond line"
echo -e $VAR

This outputs

First line
Second line

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