mario razzu
mario razzu

Reputation: 383

issue formatting file bash

I have a file(out.txt) like this:

fileOne.txt 100 ascii
fileTwo.txt 200 ascii
test        90  other

I want to create another file like this:

Filename    Size  Type
fileOne.txt 100   ascii
fileTwo.txt 200   ascii
test        90    other

and for this reason I used gawk command and my awk file is this:

BEGIN {
         print "-----------------------------------------------------\n"
         print "   Report files in directory\n\n"
         printf "\t%s\t\t%s\t\t%s\n","File Name","Size","Type"
}
   {  
     printf "\t%s\t\t%s\t\t%d\n",$1,$2,$3

}

it works for me , but my problem is this: if there is a file with long name,it's name goes also to the type column and the size value is printed all right under the size column, and I get a thing:

Filename    Type  Size
fileWithLongName.txt ascii   100
fileTwo.txt ascii 200
test        other    90

Upvotes: 0

Views: 37

Answers (1)

Rakholiya Jenish
Rakholiya Jenish

Reputation: 3223

If you can use a temporary file:

YOUR_AWK_SCRIPT_ABOVE | column -t > temp && mv temp ORIGINAL_FILENAME

column -t by default is delimit column by whitespaces. To specify a set of characters to delimit columns, you -s option.

You can use:

#name:script.awk
BEGIN{
    printf "%s\t%s\t%s\n","File Name","Size","Type"
}
{
    printf "%s\t%s\t%d\n",$1,$2,$3
}

Then:

awk -f script.awk INPUT_FILENAME | column -s $'\t' -t > temp && mv temp INPUT_FILENAME

You can add:

print "-----------------------------------------------------\n"
print "   Report files in directory\n\n"

lines later after completing above command.

Upvotes: 2

Related Questions