[英]Adding a zeros in a text file using awk
I have some text files that look like this: 我有一些看起来像这样的文本文件:
558903
5589157
55893434
55907235
.
.
.
7158709
71587172
7158748
I want to add zeros on lines that don't have the same number of characters as the other lines. 我想在字符数与其他行不同的行上添加零。
The output should look like this: 输出应如下所示:
55890300
55891570
55893434
55907235
.
.
.
71587090
71587172
71587480
Thanks in advance. 提前致谢。
这是使用awk
的另一种方式:
awk 'FNR==NR { m = (m > NF ? m : NF); next } { print $0 * 10 ** (m - NF) }' FS= file{,}
Two pass Perl solution. 两遍Perl解决方案。 It should work for huge files, too, that you can't keep in memory:
它也应该适用于大型文件,您不能将其保留在内存中:
#!/usr/bin/perl
use warnings;
use strict;
my $length = 0;
open my $IN, '<', 'input.txt' or die $!;
while (<$IN>) {
$length = length if length > $length;
}
$length--; # Ignore newlines.
seek $IN, 0, 0;
while (<$IN>) {
chomp;
print $_, '0' x ($length - length), "\n";
}
Here is a way with awk
: 这是使用
awk
的方法:
$ awk '
{
max = ((max > length($1)) ? max : length($1))
a[NR] = $1
}
END {
for(x=1; x<=NR; x++) {
n = max - length(a[x])
while(n-->0) {
a[x] = a[x] "0"
}
print a[x]
}
}' file
55890300
55891570
55893434
55907235
71587090
71587172
71587480
awk solution without storing all numbers in memory: awk解决方案,不将所有数字存储在内存中:
awk 'NR==FNR {if (length($1)>m) m=length($1); next }
length($1)<m { $1=$1*(10**(m-length($1))) } 1' file file
55890300
55891570
55893434
55907235
71587090
71587172
71587480
You can use BASH with bc
to multiply the numbers appropriately. 您可以将BASH与
bc
一起使用以将数字适当地相乘。
while read l; do
n=${#l}
if [ $n -lt 8 ] && [[ $l =~ [0-9]+ ]]; then
d=$((8-n))
echo "$l*(10^$d)"|bc
else
echo $l
fi
done < file
This will work if the highest amount of digits in the number is 8. 如果数字中的最高位数为8,这将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.