Sep 102012

This is a continuation of Bash Scripting Tricks and Techniques.


Script  Trick 3 – Hodge Podge of Useful Commands

Below are a handful of commands that I have found useful.


Command 1

ls -la . |rev |cut -d " " -f 1 |rev > FooList.txt

This command lists the contents of the current directory, reverses the output (left to right, not up and down), isolates the first field as delimited by a space, reverses it again so that it’s correctly oriented, and sends it to the file FooList.txt.


Command 2

sed -n -i '4,$ p' FooList.txt

The above command takes the file FooList.txt and removes the first three lines.  This is helpful if you want to get rid of extraneous lines from the output of ls –la, which removes 1) the total, 2) the “.” for the current directory, and 3) the “..” for the parent directory.


Command 3

find . -name "*.bz2" -exec basename {} \; |sort -r |head -n 1 > bz2.Text.temp

I used the above command in lieu of the first two commands to accomplish a similar task.  It’s particularly useful if you need to search in subdirectories.  It finds all files with a “bz2” extension and just provides the basename.  In other words, no path information is provided.  It sorts in reverse order, which was useful for finding the most recent file where part of the name was the same, but the other part of the name was tagged with the date.  It then took the first line of the output and sent it to a file called bz2.Text.temp.  So, for two files named foo.20120501.bz2 and foo.20120630.bz2, the latter file would be sent to bz2.Text.temp.




Additional Reading