简体   繁体   中英

How can I remove a newline (\n) at the end of a string?

The problem

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

  • might contain an undefined set of characters
  • may be empty. If it is empty, I want to avoid the trailing \\n .

I am open for any command line utility (sed, tr, awk, ... you name it).

Tryings

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.

Idea

There might be an approach to convert the \\n to something else. But since $LINES can contain arbitrary characters, this might be dangerous.

Sources

I skim read through the following questions

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}

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