Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad all lines with spaces to a fixed width in Vim or using sed, awk, etc

Tags:

vim

sed

awk

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.

like image 522
mathematical.coffee Avatar asked Feb 22 '12 12:02

mathematical.coffee


4 Answers

Vim

:%s/.*/\=printf('%-63s', submatch(0))
like image 183
kev Avatar answered Oct 24 '22 14:10

kev


$ awk '{printf "%-63s\n", $0}' testfile > newfile
like image 36
GambitGeoff Avatar answered Oct 24 '22 13:10

GambitGeoff


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.)

like image 43
ib. Avatar answered Oct 24 '22 12:10

ib.


Just for fun, a Perl version:

$ perl -lpe '$_ .= " " x (63 - length $_)'
like image 21
glenn jackman Avatar answered Oct 24 '22 13:10

glenn jackman