从某些文件读取时,串联字符串失败 [英] Concatenating strings fails when read from certain files

查看:32
本文介绍了从某些文件读取时,串联字符串失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个部署到服务器的Web应用程序.我正在尝试创建一个脚本,使其他东西从与应用程序一起部署的属性文件中读取Web应用程序的当前版本.

I have a web application that is deployed to a server. I am trying to create a script that amoing other things reads the current version of the web application from a properties file that is deployed along with the application.

文件如下:

//other content
version=[version number]
build=[buildnumber]
//other content

我想创建一个看起来像这样的变量: version-buildnumber

I want to create a variable that looks like this: version-buildnumber

这是我的脚本:

VERSION_FILE=myfile

VERSION_LINE="$(grep "version=" $VERSION_FILE)"
VERSION=${VERSION_LINE#$"version="}
BUILDNUMBER_LINE=$(grep "build=" $VERSION_FILE)
BUILDNUMBER=${BUILDNUMBER_LINE#$"build="}
THEVERSION=${VERSION}-${BUILDNUMBER}

奇怪的是,这在某些情况下有效,但在另一些情况下无效.我遇到的问题是当我尝试连接字符串时(即上面的最后一行).在某些情况下,它可以正常工作,但在其他情况下,一个字符串中的字符替换了另一个字符串中的字符,而不是放在后面.

The strange thing is that this works in some cases but not in others. The problem I get is when I am trying to concatenate the strings (i.e. the last line above). In some cases it works perfectly, but in others characters from one string replace the characters from the other instead of being placed afterwards.

在以下情况下无效:

  • 当我从已部署的文件中读取
  • 如果我将部署的文件复制到另一个位置并从那里读取

在以下情况下有效:

  • 如果我从头开始编写文件并从中读取文件.
  • 如果我创建自己的文件,然后将内容从部署的文件复制到我创建的文件中.

我觉得这很奇怪.那里有人知道吗?

I find this very strange. Is there someone out there recognizing this?

推荐答案

您的文件中很可能包含回车符.您可以通过在文件上运行 dos2unix 来解决此问题.

It is likely that your files have carriage returns in them. You can fix that by running dos2unix on the file.

您也许还可以在要检索的字符串上即时执行此操作.

You may also be able to do it on the fly on the strings you're retrieving.

以下是几种方法:

使用 sed 代替 grep :

VERSION_LINE="$(sed -n "/version=/{s///;s/\r//g;p}" $VERSION_FILE)"

,您将不需要Bash参数扩展来剥离"version =.

and you won't need the Bash parameter expansion to strip the "version=".

OR

按照现在的方式执行 grep ,并进行第二次参数扩展以去除回车符.

Do the grep as you have it now and do a second parameter expansion to strip the carriage return.

VERSION=${VERSION_LINE#$"version="}
VERSION=${VERSION//$'\r'}

顺便说一句,我建议习惯性地使用小写或大小写混合的变量名,以减少名称冲突的可能性.

By the way, I recommend habitually using lowercase or mixed case variable names in order to reduce the chance of name collisions.

这篇关于从某些文件读取时,串联字符串失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆