2

I need to read an ASCII file coordinates.ascii that have one line only:

-I0.00130000258937/0.000899999864241

inside a bash script, and attribute 0.00130000258937 to the variable x_inc and 0.000899999864241 to y_inc. guess that the regexp for x_inc is:

(\d.\d+)(?=/)

but I do not know the regexp for y_inc and also the sed or grep commands/syntax to implement the regexp inside the bash ..

x_inc=$(sed -n '(\d.\d+)(?=/)' coordinates.ascii )     # does not work!!!
6
  • probably the easiest way is to get the two numbers separately (two commands) Commented Jan 15, 2014 at 21:26
  • Hey, Thanks for the answer. In fact I just realize that: Commented Jan 15, 2014 at 21:39
  • coordinate=(echo "$coordinates" | grep -o "[0-9.]\+") Commented Jan 15, 2014 at 21:43
  • will create an Array variable, that can be used to assign Commented Jan 15, 2014 at 21:44
  • x_inc=${coordinate[0]} y_inc=${coordinate[1]} Commented Jan 15, 2014 at 21:44

3 Answers 3

5

Just with bash:

$ IFS="I/" read _ x_inc y_inc < coordinates.ascii
$ echo $x_inc
0.00130000258937
$ echo $y_inc
0.000899999864241
Sign up to request clarification or add additional context in comments.

3 Comments

Nice, just bash. purist ..! : )
dont forget to reset IFS with original content (IFSOld="$IFS" before and IFS="$IFSOld" after the instruction) to avoid some "strange" behavior on following instructions (if any)
@NeronLeVelu, not necessary. Notice there's no semicolon between the variable assignment and the read command. That means the variable assignment is only in place for the duration of the read command. Documented here
0

Using awk

x_inc=$(awk -F"[I/]" '{print $2}' coordinates.ascii)
echo $x_inc
0.00130000258937

y_inc=$(awk -F"[I/]" '{print $3}' coordinates.ascii)

Comments

0

Here is another version using sed and read. It reads both variables at once:

read -r x_inc y_inc <<<$(sed 's@[-I/]@ @g' < coordinates.ascii); 

# $x_inc is now: 0.00130000258937
# $y_inc is now: 0.000899999864241

Edit: or with process substitution as suggested in the comments

read -r x_inc y_inc < <(sed 's@[-I/]@ @g' < coordinates.ascii);

3 Comments

That would be a good place for a process substitution: read ... < <(sed ...)
Hey, thanks. At the beginning I did not know what I was doing .. Never worked with regexp before .. now it is clear
@glennjackman Added alternative with process substitution. Please explain why it is preferred over the first version?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.