问题描述
我正在从我的 shell 脚本中读取一个 .properties
文件.我想读取某个键的一些值,然后想将它附加到某个字符串之间,但输出很奇怪.
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"
我的Test.properties是这样的
my Test.properties is like this
Name=Pravin
Age=25
Address=Mumbai
asd=asd
执行此脚本后,我期待
ABCAddress=MumbaiDEF
但我得到的输出像
DEFAddress=Mumbai
这里会出现什么问题?
如果我在脚本中定义任何变量它都可以工作,但是当我使用命令扩展从文件中读取它时它不起作用.
If I define any variable in a script it works, but when I read it from file using command expansion it doesn't work.
推荐答案
要在扩展时从变量中修剪回车,您可以使用 ${varname%$'\r'}
.因此:
To trim carriage returns from a variable on expansion, you can use ${varname%$'\r'}
. Thus:
echo "ABC${prop_value%$'\r'}DEF"
最好将您的属性文件保存为原生 Unix 文本文件,其中根本不包含回车符.
Better would be to save your properties file as a native Unix text file, which contains no carriage returns at all.
这篇关于Shell 脚本 — 将字符串与变量连接后的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!