leroygr
leroygr

Reputation: 2509

replace path value of a variable in file with 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',

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

Upvotes: 1

Views: 2823

Answers (3)

Anitha Mani
Anitha Mani

Reputation: 867

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.

Upvotes: 0

Felix
Felix

Reputation: 116

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.

Upvotes: 0

beerbajay
beerbajay

Reputation: 20300

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"

Upvotes: 2

Related Questions