Using AWK to remove file extensions

Reading the referers of this website, I found that someone reached it querying a search engine for

awk remove file extension

Well, it’s definitely easy to achieve it if your files have just a “.” in their names. You can use this one-liner that works inverting the problem :)
# substitute jpg with the extension you need (twice in the line)
for i in $(ls *jpg | awk -F "." '{print $1}'); do mv $i.jpg $i; done

Last update: 2008-04-12

If you enjoyed this post, make sure you subscribe to my RSS feed!

9 Responses to “Using AWK to remove file extensions”


  1. 1 tannoiser

    *cough*

    rename ’s/\.jpg$//’ *.jpg

    ;)

  2. 2 Carlo

    Good answer but the original problem was about using AWK :)

  3. 3 tannoiser

    I know, Carlo, and your code is nice.
    But to me, the correct answer is “don’t”. Use the appropriate tool, it’s often a good suggestion. ;)

    (of course, this is for the original “researcher”… :))

  4. 4 Random Guy

    any idea how to make your example work on all subfolders within a directory also? i tried ls -R but it won’t work.

  5. 5 Carlo

    Random Guy:
    try with
    find folder_name -name *jpg

  6. 6 Booger

    this is great - i don’t think “tannoiser” understands how an example should illustrate a concept with an easy example so that you can modify it to real needs. In particular, I use a compiler that compiles xyz.sd into xyz.sb. So on a directory of 1000 .sd’s the easiest way to find the 3 that don’t compile is to list all of the .sds and .sbs, remove the extensions and do uniq on the list to see which have only 1 entry (not 2). And AWK is a GREAT tool to do this

  7. 7 Carlo

    Booger:
    Good :)
    A solution to your problem could be:
    l *.sd *.sb -1 | awk -F "." '{print $1}' | uniq -c | awk '$1=="1" {print $2}'

  8. 8 anonymous

    Ahh, but what if you have files like “file.txt.old”

    Then you are somewhat stuffed, as the extention gets defined to be .txt.old, rather than .old?

  9. 9 Carlo

    @anonymous:
    this is the reason I wrote

    it’s definitely easy to achieve it if your files have just a “.” in their names

    Anyway, your problem could be solved with
    for i in $(ls *.txt.old | awk -F "." '{print $1}'); do mv $i.txt.old $i.txt; done

Leave a Reply