开发者

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

开发者 https://www.devze.com 2022-12-14 21:25 出处:网络
This question already has answers here: How to split one string into multiple strings separated by at least one space in bash shell?
This question already has answers here: How to split one string into multiple strings separated by at least one space in bash shell? 开发者_JS百科 (11 answers) Closed 7 years ago.

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?


s='foo bar baz'
a=( $s )
echo ${a[0]}
echo ${a[1]}
...


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


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.


echo $line | tr " " "\n"

gives the output similar to those of most of the answers above; without using loops.


In your case, you also mention ll=<...output...>,
so, (given that I don't know much python and assuming you need to assign output to a variable),

ll=`echo $line | tr " " "\n"`

should suffice (remember to echo "$ll" instead of echo $ll)


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".


$ 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


More simple,

echo $line | sed 's/\s/\n/g'

\s --> whitespace character (space, tab, NL, FF, VT, CR). In many systems also valid [:space:]

\n --> new line


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消