I'm trying to replace every space in this text file with a backslash space.

cat prefixedfiles.txt | sed "s![[:space:]]! \!g"

Original: A a a

Result: A\ a\ a

sed 's! !\\ !g' prefixedfiles.txt

Few issues that are fixed:

  • ' instead of " prevents bash interpreting ! symbol and allows referring to backslash as \\;
  • [[:space:]] matches more than just space; you may want it or not, I used the regular space;
  • cat is superfluous here; sed can take file name as an argument (and even if it couldn't, the syntax sed < file.txt is still better than cat file.txt | sed).

Escape the backslash character.

cat prefixedfiles.txt | sed "s![[:space:]]! \\!g"

sed manual 5.3 Overview of basic regular expression syntax

Matches char, where char is one of $, *, ., [, \, or ^. Note that the only C-like backslash sequences that you can portably assume to be interpreted are \n and \\; in particular \t is not portable, and matches a ‘t’ under most implementations of sed, rather than a tab character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.