Rhys
Rhys

Reputation: 2877

How to pass an argument with spaces to sed command?

I have the below function in my shell script

fnChangeTxt()
{
        sed -i 's/<div id="'$1'"><p>*.*</<div id="'$1'"><p>'$2'</' /var/www/html/alarm.html
}

I would like use the below the pass a string to the sed command via $2 argument.

fnChangeTxt 'demo' 'This text to sed'

Hoever this doesn't work and produces and error, I assume it is due to the white spaces as the below command works fine.

fnChangeTxt 'demo' 'This_text_to_sed'

Is there a way to do this with spaces?

Thanks in advance.

Upvotes: 2

Views: 3053

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125708

Enclose the parameters ($1 etc) in double-quotes to keep them from being word-split (and prevent some other possibly unpleasant extra parsing):

sed -i "s/<div id=\"$1\"><p>*.*</<div id=\"$1\"><p>$2</" /var/www/html/alarm.html

Upvotes: 3

hcg
hcg

Reputation: 652

try using escape characters:

fnChangeTxt 'demo' 'This\ text\ to\ sed'

Upvotes: 2

Related Questions