简体   繁体   English

Shell脚本以打印具有定界符的变量

[英]Shell script to print a variable which has delimiter

I have a shell script, which gets bunch of values. 我有一个Shell脚本,它获取了一堆值。 I am segregating it based on a Delimiter(,). 我基于Delimiter(,)对其进行隔离。 Now i want to print it one by one inside a for loop. 现在我想在for循环中一个接一个地打印它。 For Eg 例如

var=/a/b/c,d/e/f/,x/y/z
for i in $(echo $var | sed "s/,/ /g")
do
echo $i
done 

Output is coming empty, Expected output is 输出为空,预期输出为

/a/b/c
d/e/f/
x/y/z

You don't need a loop. 您不需要循环。

sed 's/,/\n/g' <<< "$var"
sed 'y/,/\n/' <<< "$var"
tr ',' '\n' <<< "$var"
echo "${var//,/$'\n'}"

they all yield the desired output. 它们都能产生所需的输出。

Just to add another option - 只是添加另一个选项-

var="/a/b/c,d/e/f/,x/y/z"
while IFS=, read a b c
do printf "a=$a b=$b c=$c\n"
done <<< "$var"
a=/a/b/c b=d/e/f/ c=x/y/z

Doesn't need a loop - works fine as 不需要循环-可以正常工作

$: IFS=, read a b c <<< "$var"
$: printf "a=$a b=$b c=$c\n"
a=/a/b/c b=d/e/f/ c=x/y/z

... just wanted to show the loop structure in case it helped. ...只是想显示循环结构,以防它有所帮助。

You could read it into an array. 您可以将其读入数组。 This is quite readable: 这是很容易理解的:

var=/a/b/c,d/e/f/,x/y/z
IFS=, read -a paths <<<"$var"
for p in "${paths[@]}"; do echo "$p"; done
/a/b/c
d/e/f/
x/y/z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM