Search code examples
stringbashparameter-expansion

Bash: Replace word with spaces equal to the length of the word


I thought my bash-fu was strong enough but apparently it isn't. I can't seem to figure this out. I would like to do something like this:

  var="XXXX This is a line"
  word_to_replace="XXXX"
  # ...do something
  echo "Done:${var}"
  Done:     This is a line

Basically I want to quickly replace all characters in a word with spaces, preferably in one step. Note, if it makes things easier var currently will be at the start of the string although it may have leading spaces (which would need to be retained).

In python I would possibly do this:

>>> var="XXXX This is a line"
>>> word_to_replace="XXXX"
>>> var=var.replace(word_to_replace, ' '*len(word_to_replace))
>>> print("Done:%s" % var)
Done:     This is a line

Solution

  • Here's one way you could do it, using a combination of shell parameter expansion and the sed command.

    $ var="XXXX This is a line"
    $ word_to_replace="XXXX"
    $ replacement=${word_to_replace//?/ }
    $ sed "s/$word_to_replace/$replacement/" <<<"$var"
         This is a line
    

    ? matches any character and ${var//find/replace} does a global substitution, so the variable $replacement has the same length as $word_to_replace, but is composed solely of spaces.

    You can save the result to a variable in the usual way:

    new_var=$(sed "s/$word_to_replace/$replacement/" <<<"$var")