我想将一行中的字段提取到变量中:
aaa bbb ccc
Run Code Online (Sandbox Code Playgroud)
'aaa'=> $ a,'bbb'=> $ b,'ccc'=> $ c.如何在bash中做到这一点?
我不想管道处理,只需要将它们提取到变量或数组中.
你可以简单地做:
read a b c <<<"aaa bbb ccc"
Run Code Online (Sandbox Code Playgroud)
$ echo "a=[$a] b=[$b] c=[$c]"
a=[aaa] b=[bbb] c=[ccc]
Run Code Online (Sandbox Code Playgroud)
根据bash手册:
Here Strings
A variant of here documents, the format is:
<<<word
The word is expanded and supplied to the command on its standard input.
Run Code Online (Sandbox Code Playgroud)
最简单的是:
read a b c
Run Code Online (Sandbox Code Playgroud)
从读取行的位置进行 I/O 重定向:
while read a b c
do
# Process
done < $some_file
Run Code Online (Sandbox Code Playgroud)
如果数据已经在一个变量中,那么你可以使用:
read a b c < <(echo "$variable")
Run Code Online (Sandbox Code Playgroud)
这使用了 Bash 特定的特性,即进程替换。