简体   繁体   中英

remove leading newline from bash variable

The contents of $var are seperated by a space, so I added a loop to output each line in $var seperated by a newline into "$p" , however at the beginning a newline is also added that I can not remove.

echo "$var"

S1 S2 S3

for i in $var; do p="`echo -e "$p\\n$i"`"; done
echo -e "$p"

current

---- newline ----
S1
S2
S3

desired "$p" ---- newline removed from variable

S1
S2
S3

Tried: to remove starting newline

echo ${p} | tr -d '\n'

S1 S2 S3

To remove leading newline you can use pattern substitution

$ p="\nS1\nS2\nS3"
$ echo -e "$p"

S1
S2
S3
$ echo -e "${p/\\n/}"
S1
S2
S3

Honestly, you're overcomplicating this (and introducing some possible bugs along the way).

Just use tr to replace the spaces with newlines.

$ var="S1 S2 S3"
$ echo "$var" | tr ' ' '\n'
S1
S2
S3

Simply use echo $var | tr ' ' '\\n' echo $var | tr ' ' '\\n' to replace spaces with a new line.

This works in the cases where you have multiple spaces in the contents of var

var="S1    S2 S3"
echo $var | tr ' ' '\n'
S1
S2
S3

If you use "$var" , then you your output will have empty lines in your output which I don't think anyone would like to have.

i'd rather remove the empty line with sed first,

#!/usr/bin/env bash
var="
S1 S2 S3"

echo "$var"

sed '/^$/d' <<<"${var}" | while read i; do
  echo -n -e "[$i]"
done

S1 S2 S3
[S1][S2][S3]

You can remove a single leading newline with ${var#pattern} variable expansion.

var='
S1
S2
S3'

echo "${var#$'\n'}"

Parameter expansion can replace each space with a newline, rather than having to iterate over the sequence explicitly.

$ var="S1 S2 S3"
$ var=${var// /$'\n'}
$ echo "$var"
S1
S2
S3

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