0

I'm working with a bash script. In it I need to split a string based in the following separator: "\r\n". I tried the following:

MY_STRING='firsttext\r\nsecondtext\r\nthirdtext'
IFS='\r\n' read -ra my_array <<< "$MY_STRING"

But is not working, it split the string with the letter 'r' rather than '\r\n'. Do I need to express the separator in another way?

  • 1
    Where are you getting `MY_STRING` from? I Shouldn't it be `MY_STRING =$'firsttext\r\nsecondtext\r\nthirdtext'` ? – anubhava Aug 21 '19 at 13:49
  • Related: [Howto split a string on a multi-character delimiter in bash?](https://stackoverflow.com/q/40686922/4518341) – wjandrea Aug 21 '19 at 14:16
  • 1
    `IFS` is a list of possible single-character field separators, not a single multi-character delimiter. Also, `MY_STRING` currently does not contain carriage returns or linefeeds; it contains literal backslashes. – chepner Aug 21 '19 at 14:25

1 Answers1

2

The easiest way is to convert the multi-character delimiter to a single character -- one that's in IFS -- using parameter substitution: ${param//pattern/replacement} (where the two slashes mean global search)

my_string="firsttext\r\nsecondtext\r\nthirdtext"
read -ra my_array <<< "${my_string//\\r\\n/ }"
declare -p my_array

Output:

declare -a my_array='([0]="firsttext" [1]="secondtext" [2]="thirdtext")'

BTW, uppercase variable names should be reserved for environment variables and other special variables.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 3
    It would probably be better to replace `\\r\\n` for anything then space in case there is a space in the text. Like `${my_string//\\r\\n/'$'}` and then `IFS='$' read -ra`. One could even use unreadable characters, like `$'\01'` byte. – KamilCuk Aug 21 '19 at 13:58
  • @KamilCuk Good point. Since OP's text doesn't contain any other separators, I didn't want to overcomplicate. – wjandrea Aug 21 '19 at 14:11