简体   繁体   English

使用awk根据一行中的字符数在一行中添加零

[英]Adding zeros in a line depending on the number of characters in other lines using awk

I have some text files that look like this: 我有一些看起来像这样的文本文件:

558903
5589157
55893434
55907235
.
.
.
127158709
1271587172
127158748

I only want to change the first and last line of each file. 我只想更改每个文件的第一行和最后一行。

I want to add zeros to the first line, depending on the number of characters in the first 10 lines. 我想在第一行中添加零,具体取决于前10行中的字符数。 So for example, if in the first 10 lines, the maximum numbers of characters that had a line were 8 (like in my example) I would need to add as many zeros to my first line in order for it to have also 8 character (in this case two zeros) 因此,例如,如果在前10行中,一行的最大字符数是8(例如在我的示例中),则我需要在第一行中添加尽可能多的零,以使其也具有8个字符(在这种情况下为两个零)

I would need the same thing for my last line. 我的最后一行将需要相同的内容。 So again, I would need to check the maximum number of characters in the last 10 lines (which is 10 in my example) and add as many zeros to my last line to have as many characters (in this case just one zero). 再次重申,我需要检查最后10行中的最大字符数(在我的示例中为10),并在最后一行中添加尽可能多的零以具有尽可能多的字符(在本例中为零)。

My output should look something like this: 我的输出应如下所示:

55890300
5589157
55893434
55907235
.
.
.
127158709
1271587172
1271587480

On another post someone helped me using this script, but it add as many zeros to all lines based on the maximum number of characters in all lines (I just noticed that, that wasn't what I needed, so it was my fault not his). 在另一篇文章中,有人帮助我使用了此脚本,但是它根据所有行中的最大字符数在所有行中添加了尽可能多的零(我只是注意到,这不是我所需要的,所以这是我的错,而不是他的错)。

$ 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

Thanks in advance. 提前致谢。

Try this: 尝试这个:

awk '
NR==FNR {
    len[NR] = length($1)
    last = NR
    next
}
FNR==1 {
    for(i=1; i<=num; i++) {
        fm = ((fm>len[i])?fm:len[i])
    }
    for(j=(last); j>(last-num); j--) {
        lm = ((lm>len[j])?lm:len[j])
    }
    $1 = $1 * 10 ** (fm-length($1))
}
FNR==last {
    $1 = $1 * 10 ** (lm-length($1))
}1' num=10 file file

You can set num= to any number of lines you wish to compare. 您可以将num=设置为要比较的任何行数。 First and last lines of your file will get appended by 0 according to the max length found in this range. 根据该范围内的最大长度,文件的第一行和最后一行将附加0

Using sed, directly editing your file in place: 使用sed,直接在适当位置编辑文件:

head_max=$(( $(head -10 file.txt | wc -L) -1 ))
tail_max=$(( $(tail -10 file.txt | wc -L) -1 ))

sed -i.bk ":a 1 s/^.\{1,$head_max\}$/&0/;ta" file.txt
sed -i.bk ":a $ s/^.\{1,$tail_max\}$/&0/;ta" file.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM