Monday, November 5, 2007

Using ls to look at files by the date they were added to your system

The ls -l command displays fairly detailed information about the files in the directory you are in. It displays the date the file was last modified -- which is known in Unix as the mtime of the file. However, there are other date/time attributes on the file that might be more useful. The mtime doesn't necessarily apply to the file's last modification time on your system -- so if you've deployed an install package, it will probably show you the last time the files were modified on the system on which the package was built. This is sometimes useful for telling how old a version you have, but not really useful for much else.

The ctime is the change time, but this is not the same as the file's modification time (mtime). The ctime is the last time the file's status was changed. So, oftentimes this will be the date the file was added to your system. Very useful indeed!

This command will display the file's ctime in the date spot instead of the file's mtime:

ls -lc filename

This will show you the directory sorted by the ctime:

ls -lct

This will show you the directory sorted reverse by the ctime:

ls -lctr

Friday, June 29, 2007

Wrap long lines using fold

To line wrap a text file at 80 columns, and only break at spaces, use the command:

cat filename.txt | fold -80 -s

fold can also be told to wrap at bytes instead of columns, but I've never been quite sure how that would be useful.

Saturday, June 23, 2007

Comparing two files using comm

comm compares contents of two files. It has 3 columns available in its output — the lines only in file 1, the lines only in file 2, and the lines in both. You'll need to sort both files first.

sort test1.txt > test1-sorted.txt
sort test2.txt > test2-sorted.txt

This will show you lines only in test1.txt:

comm -23 test1-sorted.txt test2-sorted.txt

This will show you lines only in test2.txt:

comm -13 test1-sorted.txt test2-sorted.txt

This will show you lines only common to both files:

comm -12 test1-sorted.txt test2-sorted.txt

We can also do some neat tricks with uniq/sort -u:

cat test1.txt | sort > test1-sorted.txt
cat test1.txt | sort -u > test1-sorted-u.txt

This will show you lines only in test1-sorted-u.txt, which means those are the lines that appear multiple times in your original test1.txt file:

comm -13 test1-sorted.txt test1-sorted-u.txt

Neat, huh?