Wednesday, April 22, 2009

Using ls and cut to list files with a twist

Suppose you need to list files without the extension?
There are too many reasons why you might want to do this and it turns out there's a very easy way to do it. Suppose you have a directory with a bunch of files some called xyz.html and others called xyz.html.new. See examples below followed by output:

> ls
> xyz.html
> xyz.html.new

> ls | cut -d'.' -f1
> xyz
> xyz

> ls | cut -d'.' -f1,2
> xyz.html
> xyz.html

You could take this further and pipe it to sort | uniq like so:

> ls | cut -d'.' -f1,2 | sort | uniq
> xyz.html

These types of commands can be very useful for working with all kinds of files and data.

Commands used in this post: ls, cut, sort, uniq

No comments: