[英]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. $var
的内容用空格分隔,因此我添加了一个循环,以$var
将每行的换行符输出到"$p"
,但是在开始时还添加了一个我不能删除的换行符。
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 所需的“ $ p” ----从变量中删除换行符
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. 只需使用tr
用换行符替换空格。
$ var="S1 S2 S3"
$ echo "$var" | tr ' ' '\n'
S1
S2
S3
Simply use echo $var | tr ' ' '\\n'
只需使用echo $var | tr ' ' '\\n'
echo $var | tr ' ' '\\n'
to replace spaces with a new line. echo $var | tr ' ' '\\n'
用新行替换空格。
This works in the cases where you have multiple spaces in the contents of var
在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. 如果您使用"$var"
,那么您的输出中将有空行,我想没人会希望有。
i'd rather remove the empty line with sed
first, 我宁愿先用sed
删除空行,
#!/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#pattern}
变量扩展名删除单个前导换行符。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.