0

I have a string and want to print each character line by line.

Input:

str="Hello World"

Expected Output:

H
e
l
l
o

W
o
r
l
d

I tried below script, got different output

#!/bin/bash
txt="Hello World"

for i in ${txt[*]}
do
    echo $i
done

My output:

Hello
World
ks1322
  • 33,961
  • 14
  • 109
  • 164
  • 1
    [already answered here](https://stackoverflow.com/a/7579022/3833426) – John Dec 20 '22 at 15:03
  • If you must store it in an array, then `readarray txt <<< $(echo "Hello World" |grep -o .)` will do it. – John Dec 20 '22 at 15:16

1 Answers1

2

A few ideas:

Using read's ability to read n characters at a time:

while read -r -n1 i
do
    echo "$i"
done <<< "$str"

Using bash's substring ability:

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

Feeding str to grep as a here-string:

grep -o . <<< "${str}"

All of these generate:

H
e
l
l
o

W
o
r
l
d
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
  • Why not use the `readarray` bash builtin? – John Dec 20 '22 at 15:46
  • Why make a copy of the data (one copy in `str`, one copy in an array), and still require a loop (`while` vs `for`), just to print single-character lines? Nothing in OP's question indicates a need for, or a benefit from, an array. – markp-fuso Dec 20 '22 at 15:56