Replace all Occurences of '.' with '_' before '=' using sed

冷暖自知 提交于 2020-01-16 01:53:20

问题


I have a properties file as below:

build.number=153013
db.create.tablespace=0
db.create.user=0
db.create.schema=0
upgrade.install=1
new.install=0
configure.jboss=0
configure.jbosseap=false
configure.weblogic=1
configure.websphere=0

I need to import these variables into a shell script. As you know, '.' is not a valid character to use as a variable in linux. How would I use sed to replace all occurrences of '.' before the '=' with '_' . I have replaced all occurrences of '.' but there are some properties that have values which contain a '.' that I would like to not modify.

Any help is appreciated!

Thanks!


回答1:


You can use

sed -e ':b; s/^\([^=]*\)*\./\1_/; tb;'

It replaces stringWithoutEquals. with stringWithoutEquals_ for as long as the match succeeds. In effect, this replaces all the .'s before the = with _.




回答2:


You can try this:

sed 's/\.\|\(=.*\)/_\1/g;s/_=/=/' file

The approach consists to capture all the content after the equal to consume all trailing characters (including possible dots). So all dots before the equal are replaced with an underscore and an empty capture group, but there is an underscore before the equal. The second replacement removes this last underscore.




回答3:


This might work for you (GNU sed):

sed 's/=/&\n/;h;y/./_/;G;s/\n.*\n//' file

Separate the line with a marker at the =. Copy the line. Replace all .'s with _'s. Append the original line and subtract the text between the two markers.




回答4:


Here is an awk

awk -F= '{gsub(/\./,"_",$1)}1' OFS== file
build_number=153013
db_create_tablespace=0
db_create_user=0
db_create_schema=0
upgrade_install=1
new_install=0
configure_jboss=0
configure_jbosseap=false
configure_weblogic=1
configure_websphere=0

It divides the text by =, then replace in first field . with _.



来源:https://stackoverflow.com/questions/26877805/replace-all-occurences-of-with-before-using-sed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!