unix - Shell: How to append characters at the end of a string? -
i need write shell script append characters each line in text make lines same length. example, if input is:
line 1 has 25 characters. line 2 has 27 characters. line 3: lines must have same number of characters.
here "line 3" has 58 characters (not including newline
character) have append 33 characters "line 1" , 31 characters "line 2". output should like:
line 1 has 25 characters.000000000000000000000000000000000 line 2 has 27 characters.0000000000000000000000000000000 line 3: lines must have same number of characters.
we can assume max length (58 in above example) known.
here 1 way of doing it:
while read -r; # read file 1 line @ time printf "%s" "$reply" # print line without newline (( i=1; i<=((58 - ${#reply})); i++ )); # find difference in length iterate printf "%s" "0" # pad 0s done printf "\n" # add newline done < file
output:
line 1 has 25 characters.000000000000000000000000000000000 line 2 has 27 characters.0000000000000000000000000000000 line 3: lines must have same number of characters.
of course easy if know max length of line. if don't need read file in array keep track of length of each line , keeping length of line longest in variable. once have read file, iterate array , same for loop
shown above.
Comments
Post a Comment