我需要编写一个shell脚本来将字符附加到文本中的每一行,以使所有行的长度相同。例如,如果输入为:
Line 1 has 25 characters.
Line two has 27 characters.
Line 3: all lines must have the same number of characters.
这里“第3行”有58个字符(不包括newline
字符)所以我必须将33个字符附加到“第1行”,将31个字符附加到“第2行”。输出应如下所示:
Line 1 has 25 characters.000000000000000000000000000000000
Line two has 27 characters.0000000000000000000000000000000
Line 3: all lines must have the same number of characters.
我们可以假设最大长度(在上例中为58)是已知的。
答案 0 :(得分:1)
这是一种方法:
while read -r; do # Read from the file one line at a time
printf "%s" "$REPLY" # Print the line without the newline
for (( i=1; i<=((58 - ${#REPLY})); i++ )); do # Find the difference in length to iterate
printf "%s" "0" # Pad 0s
done
printf "\n" # Add the newline
done < file
Line 1 has 25 characters.000000000000000000000000000000000
Line two has 27 characters.0000000000000000000000000000000
Line 3: all lines must have the same number of characters.
当然,如果你知道线的最大长度,这很容易。如果不这样做,则需要读取数组中的文件,跟踪每行的长度,并保持变量中最长的行的长度。完全读取文件后,迭代数组并执行上面显示的for loop
。
答案 1 :(得分:1)
awk '{print length($0)}' <file_name> | sort -nr | head -1
你不需要循环来找到最长的
答案 2 :(得分:1)
这是一个神秘的:
perl -lpe '$_.="0"x(58-length)' file