如何读取一行数据并将它们分配给变量,同时还提供默认值?
我想实现这样的目标,但无法正确理解语法。
{
read variable1=${variable1:=default1} variable2=${variable2:=default2}
read variable3=${variable3:=default3} variable4=${variable4:=default4}
} <fileList
答案 0 :(得分:1)
使用循环:
while read -r var1 var2 dummy; do
var1=${var1:-default1}
var2=${var2:-default2}
# process this line
done < fileList
read -r var1 var2 dummy
- 如果一行有超过两个空格分隔的标记,则会将其读入dummy
并可以忽略答案 1 :(得分:0)
# Read in the 2 fields from the first (odd) line
while read var1 var2
do
# Read in the 2 fields from the next (even) line
read var3 var4
# Set defaults
: ${var1:=var1_default}
: ${var2:=var2_default}
: ${var3:=var3_default}
: ${var4:=var4_default}
echo "$var1 $var2 $var3 $var4"
done < foo.txt
eins zwei < line 1 (odd)
drei vier < line 2 (even)
< blank line
fünf
< blank line
sechs sieben
acht
我将file_reader.sh
的输出传输到column
命令,以使值更具可读性$ ./file_reader.sh | columnt -t
...
eins zwei drei vier
var1_default var2_default fünf var4_default
var1_default var2_default sechs sieben
acht var2_default var3_default var4_default