Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a line into words separated by one or more spaces in bash? [duplicate]

Tags:

bash

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?

like image 865
asdf Avatar asked Dec 29 '09 17:12

asdf


People also ask

How do I split a line in word bash?

The special shell variable $IFS is used in bash for splitting a string into words. $IFS variable is called Internal Field Separator (IFS) that is used to assign the specific delimiter for dividing the string. Word boundaries are identified in bash by $IFS. White space is the default delimiter value for this variable.

How do I split 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 I split a line in Linux?

If you want your file to be split based on the number of lines in each chunk rather than the number of bytes, you can use the -l (lines) option. In this example, each file will have 1,000 lines except, of course, for the last one which may have fewer lines.


2 Answers

s='foo bar baz' a=( $s ) echo ${a[0]} echo ${a[1]} ... 
like image 128
ZoogieZork Avatar answered Sep 24 '22 10:09

ZoogieZork


If you want a specific word from the line, awk might be useful, e.g.

 $ echo $LINE | awk '{print $2}' 

Prints the second whitespace separated word in $LINE. You can also split on other characters, e.g.

 $ echo "5:6:7" | awk -F: '{print $2}' 6 
like image 21
xioxox Avatar answered Sep 26 '22 10:09

xioxox