confused
confused

Reputation: 1

Replace substring of variable in sh

I'm looking to take a file name with spaces and replace the spaces with escape characters (i.e. "\ ") to use for file checking and manipulation. I'm using Bourne Shell (not bash) and I cannot use the sed command for implementation and portability reasons. I tried using parameter expansion, but I couldn't get it to work and I know that it is much less robust than in bash.

Example:

ITEM="file with spaces"            # What I have

WRAPPED_ITEM="file\ with\ spaces"  # What I need

PATTERN="\ "                       # What I tried
WRAPPED_ITEM="${ITEM/ /$PATTERN}"

Are there any workarounds for this?

Upvotes: 0

Views: 337

Answers (1)

oguz ismail
oguz ismail

Reputation: 50815

This can be done using portable variants of parameter expansions as shown below. The same algorithm should work for any character/character string on any modern POSIX shell.

quotews() {
  tmp=$1 out=
  while true; do
    case $tmp in
    *\ *) out="$out${tmp%% *}\\ "
          tmp=${tmp#* } ;;
       *) break
    esac
  done
  printf '%s\n' "$out$tmp"
}
$ quotews 'file with spaces'
file\ with\ spaces

Upvotes: 3

Related Questions