Find Longest Line in a .txt File and fill all Lines to that Length with 'blank Spaces'?
Usually I find that this type of question is a result of this thought process:
- I am trying to solve problem A
- I think doing process B will solve A
- I will ask how to achieve process B
You will get literal answers on how to achieve process B - but if you include thecontext of problem A, you will get better answers and probably one that solvesproblem A in a simpler manner than process B.
So, what problem are you trying to solve by making all the lines in a file the same length?
You can use wc
to count the number of characters in a line. Measure all lines in the file to find the longest length. For all other files, (max length - line length) gives you the number of space characters to print at the end of the line (which you can do with printf
).
Update:Is using awk
a requirement? If not, try this:
# Measure the longest line in the filemaxlen=`wc -L filename.txt | cut -d ' ' -f 1`# Pad each line to $maxlen characterswhile read linedo printf "%-${maxlen}s\n" "$line" >> outfile.txtdone < filename.txt
Edit #2:If you don't have the -L
option to wc
, you can calculate the length of the longest line using the following loop:
maxlen=0while read linedo thislen=`echo $line | wc -c` [ $[$thislen>$maxlen] ] && maxlen=$thislendone < filename.txt
The ending value of $maxlen
will be the length of the longest line.