开发者

Display characters of a variable

I am doing a bash script and I want to displa开发者_如何转开发y the characters of a variable ($VAR). What I want the script to do is (pseudo-code) :


String var = "Hello";
for (int i = 0; i < var.length(); i++) {
    System.out.println(var.substring(i, i+1));
}
The size of the variable can change, one time it can be 5 characters and the next time 6 for example. Thank you for you help! Michaël


Here's a, hopefully quite close, translation.

var="Hello"
for (( i = 0; i < ${#var}; i++ ))
do
    echo ${var:i:1}
done

Illustrates a few bash concepts.

  • ${#var} gives the number of characters in variable ${var}
  • ${var:x:y} gives a substring of characters of ${var} starting at position x, length y


An alternate approach:

echo hello | sed 's/\(.\)/\1\n/g'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜