1

I have a script which is getting value from a ".properties" file. It replaces the value successfully if it is a simple string but if contains escape characters like ('\') it does not work. Can anybody point out please that what to do, i have searched on the internet but unable to understand the "REGEX".

Script File:

#!/bin/bash
# Omer's First Script
#Include Properties File
. directoryPaths.properties
echo "Start"

sed -i "s/DONEDIRECTORY/$DoneDirectory/" *TestFile*



echo "finish"

directoryPaths.properties

DoneDirectory=/home/omerkhalid/Documents/Test/Done

TestFile.txt

This is a test Document.

DONEDIRECTORY

Error:

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

Note: If i change the value of "DoneDirectory" to simple string i.e. "Done" , it works fine. But with "/" escape characters it doesn't work.

omer khalid
  • 855
  • 1
  • 12
  • 39

3 Answers3

5

Problem is not with the sed command but with the contents of the variable $DoneDirectory.

In the sed command

sed -i "s/DONEDIRECTORY/$DoneDirectory/" *TestFile*

/ is used as the delimitter, there by sed expects only 3 slashes following the s command. But once the variable $DoneDirectory is substituted there are 8 / which gives the error

Solution

Use some other delimeters in sed like

sed -i "s#DONEDIRECTORY#$DoneDirectory#" *TestFile*
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
2

Since the variable $DoneDirectory contains sed's default command delimiter / I would use a different delimiter:

sed -i "s#DONEDIRECTORY#$DoneDirectory#" *TestFile*
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
1

I would argue that sed is not the right tool for this job. Sure, you can work with other delimiters, but if the other delimiter shows up in your string (or a backslash, or something else that sed interprets), it's still going to explode. I believe awk is better suited:

awk -v subst="$DoneDirectory" '{ sub("DONEDIRECTORY", subst); print $0 }' TestFile

Note: use gsub instead of sub if DONEDIRECTORY can show up more than once in a line and both should then be substituted.

Wintermute
  • 42,983
  • 5
  • 77
  • 80