0

I would have thought that was super simple, but here :

I want to "explode" a string into an array by tabulation and do a treatment into each string.

For information, the string comme from a mysql execution, so this string represent a row. Each field are separated by a tabulation (hence why I'm looking for exploding the string), can contain "\t" "\n" that I want to be a real tabulation / feed line, and can contain "\r\n" that I want to be replaced by "\n".

I had this function that I thought did the job

function MySQL__Untreated_String_To_Treated_Array() { local pstr_untreated_string local ltstr_treated_string_list local lstr_treated_string # Initialisation pstr_untreated_string="$1" gtReturnFonction=() # String treatment while IFS=$'\t' read -r -a ltstr_treated_string_list; do for lstr_treated_string in "${ltstr_treated_string_list[@]}"; do gtReturnFonction+=( "$(printf "%b" "$lstr_treated_string")" ) done done < <(echo "$pstr_untreated_string" | sed 's/\r\\n/\\n/g' | sed 's/\r/\\n/g') } 

BUT if my input string have multiple consecutive tabulation, it will not appear. I didn't knew, but it seem to be the normal behavior.

Then I tried multiple answer/code, but to no avail.

What I want is :

input = "" result = ( "" ) input = "\t" result = ( "" "" ) input = "\t\t" result = ( "" "" "" ) 

And ultimatly

input = "\t_SECOND_FIELD_\t\t_FOURTH_\\\t_FIELD\t_FIFTH_\r\n_FIELD_\t" result = ( "" "_SECOND_FIELD_" "" "_FOURTH_ _FIELD" "_FIFTH_ _FIELD_" "" ) 

I tried to use readarray, but failed too.

My bash version is 4.2.46 if this is important.

1 Answer 1

0

As read can't parse properly, try this :

#!/bin/bash function MySQL__Untreated_String_To_Treated_Array() { local pstr_untreated_string local ltstr_treated_string_list local lstr_treated_string # Initialisation pstr_untreated_string="$1" declare -n gtReturnFonction=$2 # String treatment while IFS= read -r ltstr_treated_string_list; do while true; do lstr_treated_string="${ltstr_treated_string_list%%$'\t'*}" gtReturnFonction+=("$lstr_treated_string") new="${ltstr_treated_string_list#$lstr_treated_string$'\t'}" test "$new" = "$ltstr_treated_string_list" && break ltstr_treated_string_list="$new" done done < <(echo "$pstr_untreated_string" | sed 's/\r\\n/\\n/g' | sed 's/\r/\\n/g') } declare -a result MySQL__Untreated_String_To_Treated_Array \ $'\t_SECOND_FIELD_\t\t_FOURTH_\\t_FIELD\t_FIFTH_\r\n_FIELD_\t'\ result declare -p result 

Output:

declare -a result=([0]="" [1]="_SECOND_FIELD_" [2]="" [3]="_FOURTH_\\t_FIELD" [4]="_FIELD_" [5]="") 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.