replace path value of a variable in file with bash

一笑奈何 提交于 2021-02-11 07:42:43

问题


I have a namelist containing inputs for simulations. I have to change the path of some variables using bash. The text file has the following value that I would like to change:

opt_path = '/home/gle/test_workflow',

I would like to replace the value of opt_path with cat and sed, and I tried the following but it doesn't work:

new_path=/my/new/path

cat namelist.wps | sed "s/^opt_path.*/opt_path = '${new_path}'/g"

it returns the following error:

sed: -e expression #1, char 29: unknown option to `s'

Someone has an idea?

EDIT: After some trials, the following code worked.

#!/bin/bash

new_path=/my/new/path
cat namelist.wps | sed "s|^.* opt_path =.*$| opt_path = '${new_path}', |g" > namelist.wps.new

Though it is working only with one whitespace between = character. How can I specify any number of whitespace between opt_path, =, and the value?

Thanks, Greg


回答1:


You have to escape slashes in regexes. Otherwise sed thinks you're ending the s command.

The new_path variable needs to look like this: \/my\/new\/path

Alternatively, you can use different separators:

sed "s|^opt_path.*|opt_path = '${new_path}'|g"




回答2:


Try this (example for bash):

#!/bin/bash

new_path=/my/new/path

echo "opt_path = '/home/gle/test_workflow'" | sed -E "s|(^opt_path[ ]*=[ ]*')([^']*)|\1$new_path|g"

I used echo instead of cat for copy and paste ready to run code.




回答3:


try this one

sed -i "s#^opt_path.*#opt_path='$new_path'#g" namelist.wps

use using delimiter as / so it would throw error message while more than one / occures in new_path variable. you can use any character as delimiter.



来源:https://stackoverflow.com/questions/20202132/replace-path-value-of-a-variable-in-file-with-bash

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