Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Script command(s) to add blanks at end of each line in a text file 3

Status
Not open for further replies.

jbmjlm10

Programmer
Jun 16, 2004
11
US
If I have a text file that looks like this:

this is the first line
line 2 is this
line 3
this is another line of this test file

I'd like to add blanks at the end of each line to make them all the same length. Let's say I want each line to be exactly 125 bytes long. That is, I want the end of line marker (hex "0a") to be moved to column 126. Each line in the file needs to padded with blanks and end up with the same number of bytes -- 125. Can this be done on a script with some unix command or sed command? Thank you for your help.
 
one way with sed:

sed -e :a -e 's/^.\{1,125\}$/& /;ta' file

sed1liners

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Another way:
awk '{print "%-125.125s\n",$0}' /path/to/input > output

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Hi:

First, I think PHV inadvertly dropped the "f" on his printf statement:

awk '{print "%-125.125s\n",$0}' /path/to/input > output

Most of the modern unix variants have an external printf statement, so you could do something like this:



while read line
do
printf "%-125.125s\n" "$line" >> new.file

done < old.file

Regards,

Ed
 
Good catch Ed
awk '{printf "%-125.125s\n",$0}' /path/to/input > output

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Thank you very much vgersh99 and PHV. They both work! The sed command works for any line length less than 256. The awk command works for any line length--I've tried over a 1000 and it still works OK. I've changed the awk command to make it into a script that can be used for any line length desired:

s=s
linelen=$1
infile=$2
outfile=$3
awk '{printf "%-'$linelen'.'$linelen''$s'\n",$0}' $infile > $outfile

Again, thank you very much for your help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top