1

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

leroygr
  • 2,349
  • 4
  • 18
  • 18
  • You're missing a filename argument to the initial `sed` command. When you say it "doesn't work", does it give an error message, or not perform the substitution? – NicholasM Nov 25 '13 at 20:02
  • Sorry I forgot the cat namelist.wps. It gives the error above. – leroygr Nov 25 '13 at 20:21

3 Answers3

2

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"

beerbajay
  • 19,652
  • 6
  • 58
  • 75
0

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.

Felix
  • 106
  • 1
  • 4
  • It is working with echo, but the variable is not changed in the file when I do: `cat namelist.wps | sed -E "s|(^opt_path[ ]*=[ ]*')([^']*)|\1$new_path|g" > namelist.new.wps` – leroygr Nov 26 '13 at 07:51
  • Could you please try if this one works: `echo "opt_path = '/home/gle/test_workflow'" | sed -E "s|(opt_path[ ]*=[ ]*')([^']*)|\1$new_path|g"` In your proposed solution you changed the regex so that opt_path is not always at the beginning of a line. – Felix Nov 26 '13 at 10:47
  • It is working with echo but now when I do it with cat on the file: `cat namelist.wps | sed -E "s|(opt_path[ ]*=[ ]*')([^']*)|\1$new_path|g"` – leroygr Nov 26 '13 at 11:00
0

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.

Anitha Mani
  • 863
  • 1
  • 9
  • 17