justaguy
justaguy

Reputation: 3022

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

Upvotes: 0

Views: 3539

Answers (6)

chepner
chepner

Reputation: 530843

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

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 140880

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

var='
S1
S2
S3'

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

Upvotes: 1

Samit
Samit

Reputation: 615

Simply use 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.

Upvotes: 1

builder-7000
builder-7000

Reputation: 7627

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

Upvotes: 4

Dyno Fu
Dyno Fu

Reputation: 9044

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]

Upvotes: 1

wjandrea
wjandrea

Reputation: 32921

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

Upvotes: 3

Related Questions