tags:

views:

410

answers:

6

Hi,

I realize how to do it in python, just with

line = db_file.readline()
ll=string.split(line)

but how can I do the same in bash? is it really possible to do it in a so simple way?

Thanks

+2  A: 

The -a option of read will allow you to split a line read in by the characters contained in $IFS.

Ignacio Vazquez-Abrams
#!/bin/bashfilename=$1while read LINEdo echo $LINE | read -adone < $filenameshould it work?
asdf
No, -a would be an argument to the first read. "help read" at a bash command line will, uh... help.
Ignacio Vazquez-Abrams
@asdf: It would look like this: `filename=$1; while read -a LINE; do echo "$LINE"; done < "$filename"`
Dennis Williamson
+1  A: 
$ line="these are words"
$ ll=($line)
$ declare -p ll  # dump the array
declare -a ll='([0]="these" [1]="are" [2]="words")'
$ for w in ${ll[@]}; do echo $w; done
these
are
words
Dennis Williamson
+1  A: 
s='foo bar baz'
a=( $s )
echo ${a[0]}
echo ${a[1]}
...
ZoogieZork
this i what i was looking for, thanks
asdf
+3  A: 

It depends upon what you mean by split. If you want to iterate over words in a line, which is in a variable, you can just iterate. For example, let's say the variable line is this is a line. Then you can do this:

for word in $line; do echo $word; done

This will print:

this
is
a
line

for .. in $var splits $var using the values in $IFS, the default value of which means "split blanks and newlines".

If you want to read lines from user or a file, you can do something like:

cat $filename | while read line
do
    echo "Processing new line" >/dev/tty
    for word in $line
    do
        echo $word
    done
done

For anything else, you need to be more explicit and define your question in more detail.

Note: Edited to remove bashism, but I still kept cat $filename | ... because I like it more than redirection.

Alok
Useless use of `cat` - redirect the file like this: `done < "$filename"`. Also, use `for value in "${var[@]}"` in this context instead of an index variable. While in this case the array may be contiguous, Bash supports sparse arrays and `${#var[@]}` may not be the last entry (although `${var[@]: -1}` will be and `indices=(${!a[@]}); count=${#indices[@]}` will give the list of indices and the correct count)
Dennis Williamson
@Dennis: All good points. I am used to `cat a | blah` instead of `blah <a' for some reason; but other points are well-taken.
Alok
+1  A: 

If you already have your line of text in a variable $LINE, then you should be able to say

for L in $LINE; do
   echo $L;
done
Novelocrat
+1  A: 

do this

while read -r line
do
  set -- $line
  echo "$1 $2"
done <"file"

$1, $2 etc will be your 1st and 2nd splitted "fields". use $@ to get all values..use $# to get length of the "fields".

ghostdog74