用bash替换文件中变量的路径值 [英] replace path value of a variable in file with bash

查看:81
本文介绍了用bash替换文件中变量的路径值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名称列表,其中包含用于模拟的输入.我必须使用bash更改某些变量的路径.文本文件具有以下我要更改的值:

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',

opt_path = '/home/gle/test_workflow',

我想用cat和sed替换opt_path的值,我尝试了以下操作,但不起作用:

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"

它返回以下错误:

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

有人有主意吗?

经过一番试验,以下代码起作用了.

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

尽管它只能在=字符之间使用一个空格.如何在opt_path,=和值之间指定 any 个空格?

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

谢谢,格雷格

推荐答案

您必须在正则表达式中转义斜线.否则, sed 会认为您正在结束 s 命令.

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

new_path 变量需要看起来像这样: \/my \/new \/path

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"

这篇关于用bash替换文件中变量的路径值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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