Alex Schittko
Alex Schittko

Reputation: 53

Exploding a file in bash

What I'm trying to do, is emulate a 2D array in a bash script on my application. (I'm an idiot for writing it in bash, but I'll re-write it once I have a working copy before my deadline)

My server.data file that I want to read from:

1:hello:there
2:im:a
3:computing:system

I know PHP ALOT better than bash, but here's a pseudo code of what I mean

foreach(line in server.data) {         
 arr = explode(":", server.data)  
  echo arr[0]    
  echo arr[1]  
  echo arr[2]  
  echo \n  
}

Would return these values:

1 hello there
2 im a
3 computing system

Can someone write a small bash script, explaining how to place each line into an array?

Upvotes: 1

Views: 2868

Answers (5)

Ingo Baab
Ingo Baab

Reputation: 608

A more general answer: If you want to imitate php's "explode" in bash with both just a string (or data coming from a file) you can use something like:

#!/bin/bash
# explode functionality in bash

data="one:two:three:and 4"

echo $data | while read line; do
   IFS=:
   set - $line
   echo $1
   echo $2
   echo $3
   echo $4
done

If your data comes on the other hand from a file, then you can redirect the contents of a file to the while loop:

  #!/bin/bash
  # explode 

  filename="data"

  while read line; do
     IFS=:
     set - $line
     echo $1
     echo $2
     echo $3
     echo $4
  done < $filename

This redirect is better than cat $filename into the while loop, because it does not need to fork another process.

Upvotes: 4

tzelleke
tzelleke

Reputation: 15345

This gives you an pseudo-2D array where you can access the individual elements by concatenating each dimension-index:

while read line
do
    ((i++))
    j=0
    IFS=:
    for e in $line
    do
        ((j++))
        lines["$i$j"]=$e
    done
done < data.txt

echo ${lines[@]}
1 hello there 2 im a 3 computing system
echo ${lines[12]}
hello

Upvotes: 0

chepner
chepner

Reputation: 531938

while IFS=: read -a arr; do
    echo "${a[@]}"
    echo -n "${arr[0]} "
    echo -n "${arr[1]} "
    echo "${arr[2]}"
done < server.data

The echo statements just demonstrate some ways to access the array; all the work is done by read -a.

Upvotes: 0

Michael Besteck
Michael Besteck

Reputation: 2423

Assuming the text file is called "x.txt":

#!/bin/bash

for line in `cat x.txt`; do
    a[${i}]=$line;
    i=$i+1;
done;

echo ${a[0]};
echo ${a[1]};
echo ${a[2]};

Upvotes: 0

Leonid Volnitsky
Leonid Volnitsky

Reputation: 9144

cat server.data | 
while read line; do  
   IFS=: 
   set - $line
   echo $1  
   echo $2  
   echo $3
done

Upvotes: 5

Related Questions