John Bergqvist
John Bergqvist

Reputation: 1003

Bash: How to split a string into an iterable series of strings, on "\n"?

If i have a string, which is as follows: :x: **Line 1**\n`Line 2`

How can I split it into 2 strings (in this case) delimited by "\n", so that I can iterate through it as follows:

for LINE in $STRING
do
   echo "Line: $LINE"
done


Line: :x: **Line 1**
Line: `Line 2`

All the other examples i've tried from here, don't seem to do that, they only print the whole string out in one go.

For example, i've tried this:

STRING=":x: **Line 1**\n\`Line 2\`"
while IFS= read -r line; do
    echo "Line: $line"
done <<< "$STRING"

and I get:

Line: :x: **Line 1**\n`Line 2`

Upvotes: 0

Views: 162

Answers (2)

markp-fuso
markp-fuso

Reputation: 34419

Converting the literal \n into a linefeed and using in a while loop:

STRING=":x: **Line 1**\n\`Line 2\`"
while IFS= read -r line; do
    echo "Line: $line"
done < <(sed 's/\\n/\n/g' <<< "${STRING}")

Or using the printf idea (including CharlesDuffy's comment):

while IFS= read -r line
do
    echo "Line: $line"
done < <(printf '%b\n' "${STRING}")

NOTE: Added the extra \n to make sure the 2nd line is terminated correctly so the while loop can read it.

Both of which should generate:

Line: :x: **Line 1**
Line: `Line 2`

Upvotes: 1

chepner
chepner

Reputation: 531165

Use a while loop.

while IFS= read -r line; do
    echo "Line: $line"
done <<< "$STRING"

Upvotes: 1

Related Questions