Search code examples
linuxbashif-statementawkls

Using Awk to Find Files ending in .c


I am writing an awk script which looks like this inside:

BEGIN{print "Name\t  Size\t\t  Access"}
{if($10~/[1-9].[c]) printf "%-10s %-10s %-5s\n", $10, $6, $1}

This tries to find files ending in .c but instead it gives me files that have .c within the name. My output looks like this:

lab1.cpp 
Lab2.cpp 
prog1.c  
prog2.c 
prog3.c.txt 

I have to use the awk command to find these files. How do I fix it this to get this:

prog1.c  
prog2.c 

Solution

  • Use end anchor in your regex and shorten your awk by removing if and conditional blocks:

    BEGIN{print "Name\t  Size\t\t  Access"}
    $10 ~ /[1-9]\.c$/ { printf "%-10s %-10s %-5s\n", $10, $6, $1}