24

How can I pad each line of a file to a certain width (say, 63 characters wide), padding with spaces if need be?

For now, let’s assume all lines are guaranteed to be less than 63 characters.

I use Vim and would prefer a way to do it there, where I can select the lines I wish to apply the padding to, and run some sort of a printf %63s current_line command.

However, I’m certainly open to using sed, awk, or some sort of linux tool to do the job too.

ib.
  • 27,830
  • 11
  • 80
  • 100
mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194

8 Answers8

37

Vim

:%s/.*/\=printf('%-63s', submatch(0))
ib.
  • 27,830
  • 11
  • 80
  • 100
kev
  • 155,172
  • 47
  • 273
  • 272
  • fantastic, thankyou! I didn't realise you could use `printf` within the replacement field in vim, I'll have to read up. – mathematical.coffee Feb 22 '12 at 12:21
  • 1
    the `.63` precision is not necessary here. – Benoit Feb 22 '12 at 13:32
  • 1
    @mathematical.coffee: Note, though, that this command does not work correctly for a multibyte encoding (like UTF-8), since `printf()` counts string width in bytes. I would recommend an [alternative solution](http://stackoverflow.com/a/9407042/254635). – ib. Feb 24 '12 at 04:52
28
$ awk '{printf "%-63s\n", $0}' testfile > newfile
ib.
  • 27,830
  • 11
  • 80
  • 100
GambitGeoff
  • 629
  • 4
  • 9
13

In Vim, I would use the following command:

:%s/$/\=repeat(' ',64-virtcol('$'))

(The use of the virtcol() function, as opposed to the col() one, is guided by the necessity to properly handle tab characters as well as multibyte non-ASCII characters that might occur in the text.)

ib.
  • 27,830
  • 11
  • 80
  • 100
3

This might work for you:

$ sed -i ':a;/.\{63\}/!{s/$/ /;ba}' file

or perhaps more efficient but less elegant:

$ sed -i '1{x;:a;/.\{63\}/!{s/^/ /;ba};x};/\(.\{63\}\).*/b;G;s//\1/;y/\n/ /' file
ib.
  • 27,830
  • 11
  • 80
  • 100
potong
  • 55,640
  • 6
  • 51
  • 83
3

Just for fun, a Perl version:

$ perl -lpe '$_ .= " " x (63 - length $_)'
ib.
  • 27,830
  • 11
  • 80
  • 100
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
2

It looks like you are comfortable using vim, but here is a pure Bash/simple-sed solution in case you need to do it from the command line (note the 63 spaces in the sed substitution):

$ sed 's/$/                                                               /' yourFile.txt |cut -c 1-63
ib.
  • 27,830
  • 11
  • 80
  • 100
2

With sed, without a loop:

$ sed -i '/.\{63\}/!{s/$/                                                                /;s/^\(.\{63\}\).*/\1/}' file

Be sure to have enough spaces in the 1st substitution to match the number of space you want to add.

ib.
  • 27,830
  • 11
  • 80
  • 100
jfg956
  • 16,077
  • 4
  • 26
  • 34
1

Another Perl solution:

$ perl -lne 'printf "%-63s\n", $_' file
ib.
  • 27,830
  • 11
  • 80
  • 100
Chris Koknat
  • 3,305
  • 2
  • 29
  • 30