Reputation: 1966
I have multiple property lines in a single string separated by \n
like this:
LINES2="Abc1.def=$SOME_VAR\nAbc2.def=SOMETHING_ELSE\n"$LINES
The LINES
variable
\n
.I am open for any command line utility (sed, tr, awk, ... you name it).
I tried this to no avail
sed -z 's/\\n$//g' <<< $LINES2
I also had no luck with tr, since it does not accept regex.
There might be an approach to convert the \n
to something else. But since $LINES
can contain arbitrary characters, this might be dangerous.
I skim read through the following questions
Upvotes: 0
Views: 226
Reputation: 241721
Here's one solution:
LINES2="Abc1.def=$SOME_VAR"$'\n'"Abc2.def=SOMETHING_ELSE${LINES:+$'\n'$LINES}"
The syntax ${name:+value}
means "insert value
if the variable name
exists and is not empty." So in this case, it inserts a newline followed by $LINES
if $LINES
is not empty, which seems to be precisely what you want.
I use $'\n'
because "\n"
is not a newline character. A more readable solution would be to define a shell variable whose value is a single newline.
It is not necessary to quote strings in shell assignment statements, since the right-hand side of an assignment does not undergo word-splitting nor glob expansion. Not quoting would make it easier to interpolate a $'\n'
.
It is not usually advisable to use UPPER-CASE for shell variables because the shell and the OS use upper-case names for their own purposes. Your local variables should normally be lower case names.
So if I were not basing the answer on the command in the question, I would have written:
lines2=Abc1.def=$someVar$'\n'Abc2.def=SOMETHING_ELSE${lines:+$'\n'$lines}
Upvotes: 1