Spliting bash string into parts

Hello, let's say I have this string:

string1="A\nB\nC D E\nFG\nH";

How can I split it so as to take every string separated with '\n' separately?
For example, as for $string1, it would be split into
string1_part1="A"
string1_part2="B"
string1_part3="C D E"
string1_part4="FG"
string1_part5="H"

i tried to do this way:

for i in $string1; do
   mpla mpla
done

but this way takes spaces as separators too, so that didn't work :confused:

Thanks in advance for any answers!:b:

#!/usr/bin/bash              
string1="A\nB\nC D E\nFG\nH";
echo $string1 >temp          
while read a                 
do                           
echo "$a"                    
done <temp   

Yes it's possible but I'm sure you don't need it.
Did your try your string in bash:

string1="A\nB\nC D E\nFG\nH"
echo "$string1"

I believe you need learn some basic stuff before. The semicolon at the end of the assignment says about this too.

What about this:

#!/bin/bash

## Define a string
string1="A\nB\nC D E\nFG\nH"

## Replace the \n's with a single character, since IFS
## can only be 1 character.
match='\\n'
replacement='|'
string2=$(echo ${string1//${match}/${replacement}})

## Change the input field seperator to $replacement
IFS="$replacement"

## Parse the string based on the IFS.
set -- $string2

echo "1: $1"
echo "2: $2"
echo "3: $3"
echo "4: $4"
echo "5: $5"

Output:

$ test2
1: A
2: B
3: C D E
4: FG
5: H
$

Simpler way for bash or newer ksh or even ash:

#!/bin/bash 
string1="A\nB\nC D E\nFG\nH"
OLDIFS="$IFS"
IFS="
"
        set -- `echo -e "$string1"`
IFS="${OLDIFS}"

echo $1
echo $2
echo $3
echo $4

In some shells you can remove the -e.

1 Like

Last reply-best reply