2
#!/bin/bash a="2015-05-14 14:55:12.916395602 +0530Ttest_12345" IFS='T' readarray -t ADDR <<< "$a" echo "${ADDR[@]:1}" 

I am trying to split the string a into time and name using the delimiter T. On printing the first element in the result array ADDR, it prints an empty string however.

How to convert the string with delimiter into array elements?

1
  • 1
    Rather strange way... echo ${a%T*} ${a#*T} is enough
    – Costas
    CommentedMay 14, 2015 at 17:44

2 Answers 2

2

readarray read lines from standard input into array, so you can do something like this:

$ a="2015-05-14 14:55:12.916395602 +0530Ttest_12345" $ readarray -t ADDR <<<"$(tr T '\n'<<<"$a")" $ printf %s\\n "${ADDR[0]}" 2015-05-14 14:55:12.916395602 +0530 $ printf %s\\n "${ADDR[1]}" test_12345 

But you don't need an array at all, you can use parameter expansion:

$ a="2015-05-14 14:55:12.916395602 +0530Ttest_12345" $ printf %s\\n "${a%T*}" 2015-05-14 14:55:12.916395602 +0530 $ printf %s\\n "${a##*T}" test_12345 
    1

    cuonglm's answer is right, you should probably use parameter expansion in that context. However, I though a working example on the use of IFS was missing :

    $ IFS=T read -a ADDR <<<"2015-05-14 14:55:12.916395602 +0530Ttest_12345" $ echo ${ADDR[0]} 2015-05-14 14:55:12.916395602 +0530 $ echo ${ADDR[1]} test_12345 

      You must log in to answer this question.