我知道如何在python中做到这一点,只是用
line = db_file.readline()
ll=string.split(line)
Run Code Online (Sandbox Code Playgroud)
但我怎样才能在bash中做同样的事情呢?是否真的有可能以这么简单的方式做到这一点?
Zoo*_*ork 132
s='foo bar baz'
a=( $s )
echo ${a[0]}
echo ${a[1]}
...
Run Code Online (Sandbox Code Playgroud)
xio*_*xox 34
如果你想要一行中的特定单词,awk可能是有用的,例如
$ echo $LINE | awk '{print $2}'
在$ LINE中打印第二个空格分隔的单词.您还可以拆分其他字符,例如
$ echo "5:6:7" | awk -F: '{print $2}'
6
Alo*_*hal 30
这取决于你分裂的意思.如果你想迭代一行中的单词,这是一个变量,你可以迭代.例如,假设变量line是this is a line.然后你可以这样做:
for word in $line; do echo $word; done
Run Code Online (Sandbox Code Playgroud)
这将打印:
this
is
a
line
Run Code Online (Sandbox Code Playgroud)
for .. in $var$var使用值中的值进行拆分$IFS,其默认值表示"拆分空白和换行符".
如果要读取用户或文件中的行,可以执行以下操作:
cat $filename | while read line
do
echo "Processing new line" >/dev/tty
for word in $line
do
echo $word
done
done
Run Code Online (Sandbox Code Playgroud)
除此之外,您需要更明确地更详细地定义您的问题.
注意:编辑删除bashism,但我仍然保留,cat $filename | ...因为我喜欢它比重定向更多.
har*_*wla 17
echo $line | tr " " "\n"
Run Code Online (Sandbox Code Playgroud)
给出与上述大多数答案类似的输出; 不使用循环.
在你的情况下,你也提到ll=<...output...>,
所以,(鉴于我不太了解python并假设你需要将输出分配给变量),
ll=`echo $line | tr " " "\n"`
Run Code Online (Sandbox Code Playgroud)
应该足够了(记得echo "$ll"代替echo $ll)
Pau*_*ce. 10
$ 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
Run Code Online (Sandbox Code Playgroud)
gho*_*g74 10
做这个
while read -r line
do
set -- $line
echo "$1 $2"
done <"file"
Run Code Online (Sandbox Code Playgroud)
$ 1,$ 2等将是你的第一和第二分裂"领域".使用$ @获取所有值.使用$#来获取"字段"的长度.
小智 5
更简单,
echo $line | sed 's/\s/\n/g'
Run Code Online (Sandbox Code Playgroud)
\ s->空格字符(空格,制表符,NL,FF,VT,CR)。在许多系统中,也有效的[:space:]
\ n->新行