我想问你如何在同一个文件(例如CONV.inp)中添加一组包含三个值的字符串,一个接一个地?
我想输入 N 行以及各自的值,如下所示:
...
5.834,-54.05,0
7.728,-10.35,0
7.796,-14.85,0
7.871,-4.85,0
9.397,7.09,0
...
最后的 0 永远不会改变。我将能够键入每行的两个值,并且只有当我完成时,键入一个随机字母以退出 bash 中的循环。
...
echo -en '\n'
echo "1"
echo -en '\n'
read A
read B
echo "$A,$B,0" >> CONV.inp
echo -en '\n'
echo "2"
echo -en '\n'
read C
read D
echo "$C,$D,0" >> CONV.inp
echo -en '\n'
echo "3"
echo -en '\n'
read E
read F
echo "$E,$F,0" >> CONV.inp
...
有谁知道如何使用这些功能实现循环?
提前致谢!
答案1
实际上,您想要的是在脚本中使用 do-while 样式的循环,并用于read variable1 variable2
同时读取两个值。
#!/bin/bash
# get rid of output_file.txt if it exists, write new file
# This is optional
[ -f output_file.txt ] && rm output_file.txt
# Read input once, then go into loop and start testing
# User's input
counter=0
read -p "Enter line #$counter or q to quit:" v1 v2
while [ "$v1" != "q" ]
do
printf "%s,%s,0\n" "$v1" "$v2" >> output_file.txt
counter=$(( $counter+1))
read -p "Enter line vs #$counter or q to quit:" v1 v2
done
测试运行:
$ ./read_double_input.sh
Enter line #0 or q to quit:5.834 -54.05
Enter line vs #1 or q to quit:7.728 -10.53
Enter line vs #2 or q to quit:7.96 -14.85
Enter line vs #3 or q to quit:q
$ cat output_file.txt
5.834,-54.05,0
7.728,-10.53,0
7.96,-14.85,0