1

I have a file store version information and I wrote a shell to read two fields and combine them. But when I concatenate those two fields, it show me a werid result.

version file:

buildVer = 3
version = 1.0.0

script looks like:

#!bin/bash

verFile='version'
sdk_ver=`cat $verFile | sed -nE 's/version = (.*)/\1/p'`
build_ver=`cat $verFile | sed -nE 's/buildVer = (.*)/\1/p'`
echo $sdk_ver
echo $build_ver
tagname="$sdk_ver.$build_ver"
echo $tagname

The output shows

1.0.0
3
.30.0

I tried to echo the sdk_ver directly without read it from file, this piece of script works well. So I think it may relate to the sed, but I couldn't figure out how to fix it.

Does anyone know why it acts like that?

2power10
  • 1,259
  • 1
  • 11
  • 33
  • Not your main problem, but you have two examples of [useless use of cat](http://stackoverflow.com/a/16619430/253056) in there. – Paul R Oct 10 '16 at 07:19

2 Answers2

2

You're getting this problem because of presence of DOS line ending i.e. \r in each line of version file.

Use dos2unix or this sed command to remove \r first:

sed -i 's/\r//' version

btw you can also simplify your script using pure BASH constructs like this:

#!/bin/bash

while IFS='= ' read -r k v; do
   declare $k="$v"
done < <(sed $'s/\r//' version)

tagname="$version.$buildVer"
echo "$tagname"

This will give output:

1.0.0.3
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Alternate solution, with awk:

awk '/version/{v=$3} /buildVer/{b=$3} END{print v "." b}' version.txt

Example:

$ cat file.txt 
buildVer = 3
version = 1.0.0

$ awk '/version/{v=$3} /buildVer/{b=$3} END{print v "." b}' file.txt 
1.0.0.3
heemayl
  • 39,294
  • 7
  • 70
  • 76