Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into array Shellscript

Tags:

How can I split a string into array in shell script?

I tried with IFS='delimiter' and it works with loops (for, while) but I need an array from that string.

How can I make an array from a string?

Thanks!

like image 950
Gábor Varga Avatar asked Apr 12 '12 19:04

Gábor Varga


People also ask

How do you split a string into an array in Unix?

Using the tr Command to Split a String Into an Array in Bash It can be used to remove repeated characters, convert lowercase to uppercase, and replace characters. In the bash script below, the echo command pipes the string variable, $addrs , to the tr command, which splits the string variable on a delimiter, ; .

How do I split a string in Bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.

How do you split a line in a word in shell script?

The -a option of read will allow you to split a line read in by the characters contained in $IFS . #!/bin/bash filename=$1 while read LINE do echo $LINE | read -a done < $filename should it work?


1 Answers

str=a:b:c:d:e
set -f
IFS=:
ary=($str)
for key in "${!ary[@]}"; do echo "$key ${ary[$key]}"; done

outputs

0 a
1 b
2 c
3 d
4 e

Another (bash) technique:

str=a:b:c:d:e
IFS=: read -ra ary <<<"$str"

This limits the change to the IFS variable only for the duration of the read command.

like image 110
glenn jackman Avatar answered Oct 20 '22 12:10

glenn jackman