How to pad strings with spaces in a Unix shell script?

I have data that looks like this:

01234567
09876544
12345676
34576980

I need to pad this with 11 spaces i.e. my output should look like this:

' 01234567'
' 09876544'
' 12345676'
' 34576980'

How can I do it using UNIX shell scripting?

2

5 Answers

I'm assuming/guessing that the apostrophes are not supposed to be included in the output.

Standard shell solution, where infile is the file containing the input:

while read i; do printf "%19s\n" "$i"; done < infile

where 19 is the string length per row as they are given (8) plus the wanted padding (11). I'm again guessing that this kind of padding is what you want, and not just prepending 11 spaces to all lines. If this is not the case, you need to give a specific example of how input rows of differing length should be handled.

If the apostrophes were meant to be included:

while read i; do printf "'%19s'\n" "$i"; done < infile

A shorter option from GNU coreutils is the pr command:

pr -T -o 11 foo.txt

Excerpt from man page:

DESCRIPTION Paginate or columnate FILE(s) for printing. -o, --indent=MARGIN offset each line with MARGIN (zero) spaces -T, --omit-pagination omit page headers and trailers, eliminate any pagination by form feeds set in input files

You can use Ex-editor (Vi), either by changing the file in-place:

ex -s +"%s@^@ @" -cwq foo.txt

or by parsing the standard input and print it into standard output:

cat foo.txt | ex -s +"%s@^@ @" +%p -cq! /dev/stdin

Assuming the data is in a text file:

 $ cat file.txt 01234567 09876544 12345676 34576980

Use sed command or a Perl one-liner as follows:

 $ sed -n "s#^\(.*\)#\' \1\'#p" file.txt ' 01234567' ' 09876544' ' 12345676' ' 34576980'
-n : By default, each line of input is echoed to the standard output after all of the commands have been applied to it. The -n option suppresses this behavior. p : Print the current pattern space. $ perl -p -e "s#^(.*)#\' \$1\'#" file.txt ' 01234567' ' 09876544' ' 12345676' ' 34576980'
−p: Assumes an input loop around the script. Lines are printed.
−e commandline:
May be used to enter a single line of script. Multiple −e commands
build up a multiline script.

I have tried these commands on Ubuntu Linux.

This is a supplyment to @Daniel Andersson's answer, in case the length of each line read from a file varies, you can do as following:

while read i; do printf "%11s%s\n" "" "$i"; done < infile
6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like