4

In a bash script, files with spaces show up as "File\ with\ spaces.txt" and I want to substitute those slashed-spaces with either _ or +.

How can I tell sed to do that? I had no success using;

$1=~/File\ with\ spaces.txt
ext=$1
web=$(echo "$ext" | sed 's/\ /+/')

I'm open to suggestions if there's a better way than through sed.

[EDIT]: Foo Bah's solution works well, but it substitutes only the first space because the text following it is treated as arguments rather than part of the $1. Any way around this?

octosquidopus
  • 3,517
  • 8
  • 35
  • 53

4 Answers4

3
sed 's/\\\\ /+/';

\\\\ evaluates to a \\ at the shell level, and then into a literal \ within sed.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 2
    If you'd used double quotes, you would be right; because you used single quotes, the shell doesn't remove a layer of backslashes. – Jonathan Leffler Sep 12 '11 at 21:49
2

you want to escape the slash:

web=$(echo "$ext" | sed 's/\\ /_/g')
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Foo Bah
  • 25,660
  • 5
  • 55
  • 79
  • No, that's wrong. That would replace an actual backslash+space. – thule Sep 12 '11 at 21:24
  • That's what the question (or question title) asks for - the output from bash includes a backslash and the combination of backslash+space needs to be replaced with underscore. OTOH, I suppose there is a possibility that the question (question body) is not quite sure what it needs. – Jonathan Leffler Sep 12 '11 at 21:47
  • letitbee's solution worked best. `sed 's/\ /+/g'` is what I was looking for. – octosquidopus Sep 12 '11 at 22:21
2

Sed recognises \ as space just fine:

bee@i20 ~ $ echo file\ 123 | sed 's/\ /+/'
file+123

Your bash script syntax is all wrong, though. Not sure what you were trying to do with the script, but here is an example of replacing spaces with +:

ext=~/File\ with\ spaces.txt
web=`echo "$ext" | sed 's/\ /+/g'`
echo $web

Upd: Oh, and you need the g flag to replace all occurences of space, not only the first one. Fixed above.

thule
  • 4,034
  • 21
  • 31
0

single quotes are your friend the following should be used with single quoted args for $1 and $2

#!/bin/bash
ESCAPE='\\'
if [ $# -ne 2 ];then   
  echo "$0 <TO_ESCAPE> <IN_STRING>"
  echo args should be in single quotes!! 
  exit 1
fi

TO_ESCAPE="${1}"
IN_STRING="${2}"

if [ ${TO_ESCAPE} = '\' ];then
  TO_ESCAPE='\\'
fi
echo "${IN_STRING}" | sed "s/${TO_ESCAPE}/${ESCAPE}${TO_ESCAPE}/g"