0

I would like to ask you how can I add a set of strings containing three values each, one after the other, in the same file (e.g. CONV.inp)?

I would like to type N number of lines with the respective values like here:

...

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  

...

The last 0 never change. I would be able to type the two values of each line, and only and only when I finish, typing a random letter to quit from the loop in 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 
...

Does anyone have an idea on how to implement a loop with these features?

Thanks in advance!

2
  • Why not write the file with first_column,second_column,third_column triples and then add the final zero with <input.txt sed -e 's/$/,0/'? Mar 8, 2017 at 18:44
  • Dear Gregory, thanks for the hint, but for the final goal this solution is not really efficient. Thanks again!
    – Tommy
    Mar 9, 2017 at 9:28

1 Answer 1

0

What you want , effectively, is have a do-while style of loop in your script and use read variable1 variable2 to read both values at once.

#!/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

Test run:

$ ./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
1
  • Dear Serg, this is exactly what I am looking for. Now I gonna test your piece of code trying to implant it in mine. Really thanks a lot for the hint!
    – Tommy
    Mar 9, 2017 at 9:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .