mezda
mezda

Reputation: 3647

rearrange a file contents in n number of columns

i have a file with contents as :

        000000000000000000000000
00000000000000000000000000000000
0000000000000000000000001f000000
01000000060000000000000034000000
3f000000000000000000000004000000
000000001b0000000900000000000000
00000000600300001000000009000000
010000000400000008000000

i want to rearrange its contents by specifying the number of col's. for eg., if i say the no of col's to be 80, the output should be like :

00000000000000000000000000000000000000000000000000000000000000000000000000000000
1f000000010000000600000000000000340000003f00000000000000000000000400000000000000
1b000000090000000000000000000000600300001000000009000000010000000400000008000000

can anyone help me with this ? can xxd serve the purpose here ? thanks.

Upvotes: 0

Views: 143

Answers (2)

acraig5075
acraig5075

Reputation: 10756

And as the question is also tagged C, here is a C way of doing the same:

#include <stdio.h>

int main(void)
{
    FILE* fp;
    int c, col;

    fp = fopen("datafile.txt", "r");

    col = 0;

    while ((c = fgetc(fp)) != EOF)
    {
        if (c == ' ' || c == '\n') // ignore spaces and newline
            continue;

        putchar(c); // output to stdout
        ++col;

        if (col == 80) // newline at column 80
        {
            putchar('\n');
            col = 0;
        }
    }

    fclose(fp);

    return 0;
}

Upvotes: 1

Shawn Chin
Shawn Chin

Reputation: 86924

You can use tr to first remove the whitespaces from the content, then use fold to wrap them at a specific line width.

cat infile.txt | tr -d "[:space:]" | fold -80

Upvotes: 6

Related Questions