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

后端 未结 8 1772
日久生厌
日久生厌 2021-02-02 12:33

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

相关标签:
8条回答
  • 2021-02-02 12:42

    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.

    0 讨论(0)
  • 2021-02-02 12:52

    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
    
    0 讨论(0)
  • 2021-02-02 12:53

    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
    
    0 讨论(0)
  • 2021-02-02 12:56

    Just for fun, a Perl version:

    $ perl -lpe '$_ .= " " x (63 - length $_)'
    
    0 讨论(0)
  • 2021-02-02 12:56

    Another Perl solution:

    $ perl -lne 'printf "%-63s\n", $_' file
    
    0 讨论(0)
  • 2021-02-02 12:57

    Vim

    :%s/.*/\=printf('%-63s', submatch(0))
    
    0 讨论(0)
提交回复
热议问题