JM88
JM88

Reputation: 477

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. 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)

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).

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.

Upvotes: 1

Views: 83

Answers (2)

jaypal singh
jaypal singh

Reputation: 77105

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. First and last lines of your file will get appended by 0 according to the max length found in this range.

Upvotes: 1

Josh Jolly
Josh Jolly

Reputation: 11786

Using sed, directly editing your file in place:

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

Upvotes: 0

Related Questions