Replace spaces

Hi guys, so I have another issue. Can I use sed to replace spaces in a string or variable with %20

I am having trouble with using curl on URL's containing spaces

Thanks!

post sample input and output record

string=$( printf "%s\n" "$string" | sed 's/ /%20/g' )

Or. with bash or ksh93:

string=${string// /%20}

this is a sample of the code I have to get the file "GetSeries.php.xml" from thetvdb.com

series_name="green hornet"

curl -s -o /Users/rtipton/Desktop/GetSeries.php.xml "http://thetvdb.com/api/GetSeries.php?seriesname=$series_name"

When I run this, I get a bunch of results in the xml for tv shows including "green" in the title. Curl doesn't include anything after the first space in the URL.

I'm not sure what output I could provide in this instance, let me know if I can give more

Thanks again Vid

Hey thanks cfajohnson, that did the trick, the second suggestion works perfectly!

Thanks again for being so helpful guys, I really appreciate it.

you can try something like this

 
series_name=`echo "$series_name"|sed 's/ /%20/g'`

Nice this works as well. Too many good options here! You guys are good, thanks again!

Rob

If your shell support parameter expansion this is the best solution.

Not necessarily.

Writing a portable script may be more important than writing the most efficient one.

Hey cfa!

string=${string// /%20}

This ended up working in Mac OS X but not in ubuntu hardy, I was getting an error so I ended up using vid's solution:

series_name=`echo "$series_name"|sed 's/ /%20/g'`

This works just fine on ubuntu hardy.

Do you know a lot about sed? I used vid's solution for extracting a number in between <seriesid></seriesid> in an xml file and it worked fine in Mac OS X but when I tried it in ubuntu hardy the output is blank, no number, nothing.

mind taking a look? Here is the sample XML

<Data>

<Series>
<seriesid>73545</seriesid>
<language>en</language>
<SeriesName>Battlestar Galactica (2003)</SeriesName>
<banner>graphical/73545-g11.jpg</banner>

<Overview>blah blah blah blah</Overview>
<FirstAired>2003-12-01</FirstAired>
<IMDB_ID>tt0407362</IMDB_ID>
<zap2it_id>SH710749</zap2it_id>
<id>73545</id>
</Series>
</Data>

and here is the solution given to me by vid to extract "73545" and set it to a variable

variable=`sed -ne 's/\(^\<seriesid\>\)\(.*\)\(\<\/seriesid\>\)/\2/p' filename|head -1`

If you can give me the definition of portable maybe I'll reevaluate my concept's of efficiency :cool:

It will work on Ubuntu if you specify that it is to be executed by bash. Use a shebang as the very first line of the file:

#!/bin/bash

(Check that bash is indeed in /bin.)

I avoid sed for anything beyond a simple search and replace. You get much more understandable (and thus easier-to-debug) code with awk.

awk -F '[<>]' '/^<seriesid>/ { print $3 }' filename

A portable script will run on any modern (i.e., POSIX) system. That means using only POSIX shell syntax and features and standard POSIX/Unix commands.