I am looking for a command line or bash script that would add space 5 times before the beginning of each line in a file.

for example:


after adding spaces 5 times


With GNU sed:

sed -i -e 's/^/     /' <file>

will replace the start of each line with 5 spaces. The -i modifies the file in place, -e gives some code for sed to execute. s tells sed to do a subsitution, ^ matches the start of the line, then the part between the second two / characters is what will replace the part matched in the beginning, i.e., the start of the line in this example.

  • I think I like the simplicity of your answer more as opposed to the others I've seen. – SailorCire May 5 '15 at 17:12
  • This is a great answer btw. I love it when each step is explained. I know this is old, but props and thanks. – saleetzo Mar 28 '18 at 19:49

You can use sed

sed 's_^_     _' tmpin > tmpout

Or awk

awk '{print "     " $0}' tmpin > tmpout

Or paste (Thanks cuonglm)

:| paste -d' ' - - - - - file

Watch out. These can be addictive. You can solve many simple problems, but the time will come where you need to upgrade to a full scripting language.

Edit: Sed script simplified based on Eric Renouf's answer.

  • True, I just find it helpful to think in this way, because I nearly always use sed and awk in pipes. – JosiahYoder-deactive except.. May 5 '15 at 17:16

You can use many standard tools, example with paste:

:| paste -d' ' - - - - - file

or shorter with awk:

awk '{$1="     "$1}1' file

or more portable with perl:

perl -pe '$_=" "x5 .$_' file
  • 1
    sir can you explain what : | does? – Edward Torvalds May 5 '15 at 19:19
  • 1
    It's no-op operator – cuonglm May 6 '15 at 1:27
  • :| means run the command :, which successfully does nothing and outputs nothing (explained by builtins(1)), and then the pipe | passes that command's standard output as standard input into paste(1). – Josip Rodin Mar 16 '17 at 15:53
  • Perhaps a clearer version of the above paste invocation would be paste -d' ' - - - - - file < /dev/null – Josip Rodin Mar 16 '17 at 15:58

You can use Vim in Ex mode:

ex -sc '%s/^/     /|x' file
  1. % select all lines

  2. s substitute

  3. x save and close

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