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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

padding lines in a file 1

Status
Not open for further replies.

bi

Technical User
Apr 13, 2001
1,552
US
I need help in figuring out a script.

We receive a text file with fixed length fields. However, sometimes the last 3 fields aren't used. sometimes it's just the last 2 fields that aren't used.

I need to figure out a way to count the characters in each line and then add spaces on the line to reach 140.

So, for example, if the line comes up to 120 characters long, I have to pad that line with 20 more spaces at the end of the line. If the lines comes up to 138 lines, I have to add 2 more spaces at the end of the line.

Help!
 
Try this awk script
Code:
{
  while (length < 140) {
    $0 = $0 &quot; &quot;
  }
  print
}
Hope this helps. CaKiwi
 
CaKiwi,

Thanks. My scripting talents (especially awk) are very poor so please bear with me.

How do I get the script to read the file (say, file1) and then output it to file2?
 
if you put the script in a file, script.awk say, you can enter
Code:
awk -f script.awk file1
Alternatetively, enter
Code:
awk '{while (length<140) $0=$0 &quot; &quot;; print}' file1
Both methods will send the output to stdout. Add > file2 to the end of each to send the output to file2.

Hope this helps.


CaKiwi
 
PERFECT!

Thank you, thank you, thank you.
 
Q

Is the method you described faster or more efficient than just using printf? Like this

awk '{ printf(&quot;%-140s\n&quot; , $0) }' file1

I may just be relying on my C experience. Maybe this printf is doing the exact same thing, but using more overhead.

Any clarification would be helpful - for me at least.
Einstein47
(Love is like PI - natural, irrational, endless, and very important.)
 
I suspect your method may be a little faster, especially if most lines needed a lot of padding. If most lines did not need padding, then my method might be faster. Maybe you could create a large file to test both of them and post the results. In any case, your method seems more elegant. CaKiwi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top