0

I am reading a .properties file from my shell script. I wanted to read some value for some key and after that want to append it in between some string but the output is weird.

#!/bin/bash
# Script used to read Property File
FILE_NAME="Test.properties"
prop_value=$(cat ${FILE_NAME} | grep Address)
echo "ABC${prop_value}DEF"

my Test.properties is like this

Name=Pravin
Age=25
Address=Mumbai
asd=asd

After executing this script I am expecting

ABCAddress=MumbaiDEF 

but I am getting output like

DEFAddress=Mumbai 

What would be the problem here?

If I define any variable in a script it works, but when I read it from file using command expansion it doesn't work.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
pkadam
  • 3
  • 2
  • 3
    Your file is in DOS format. It contains carriage returns, which send the cursor to the beginning of the line when printed. – Charles Duffy Feb 28 '17 at 14:50
  • BTW, you've got other bugs in here that http://shellcheck.net/ will catch. – Charles Duffy Feb 28 '17 at 14:51
  • Amongst other issues with the code, see [UUoC — Useless Use of `cat`](https://stackoverflow.com/questions/11710552/useless-use-of-cat). I'm sure this is a duplicate; finding the duplicate will be harder (and probably not worth the effort). – Jonathan Leffler Feb 28 '17 at 15:01

1 Answers1

1

To trim carriage returns from a variable on expansion, you can use ${varname%$'\r'}. Thus:

echo "ABC${prop_value%$'\r'}DEF"

Better would be to save your properties file as a native Unix text file, which contains no carriage returns at all.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441