add space 5 times at the beginning of each line in a text file

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.

Method 3

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

Method 4

You can use Vim in Ex mode:

ex -sc '%s/^/     /|x' file
  1. % select all lines
  2. s substitute
  3. x save and close


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x