31

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:

abc

after adding spaces 5 times

      abc
0

4 Answers 4

44

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.

2
  • I think I like the simplicity of your answer more as opposed to the others I've seen.
    – SailorCire
    May 5, 2015 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, 2018 at 19:49
12

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.

1
  • True, I just find it helpful to think in this way, because I nearly always use sed and awk in pipes. May 5, 2015 at 17:16
7

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
4
  • 1
    sir can you explain what : | does? May 5, 2015 at 19:19
  • 1
    It's no-op operator
    – cuonglm
    May 6, 2015 at 1:27
  • 1
    :| 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). Mar 16, 2017 at 15:53
  • 1
    Perhaps a clearer version of the above paste invocation would be paste -d' ' - - - - - file < /dev/null Mar 16, 2017 at 15:58
0

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.