December 25, 2010

How to make a banner from the command line

I thought I'd send out some command line Christmas cheer. What better way than to use figlet.

mike@shiner $ figlet 'Merry XMAS!'
 __  __                       __  ____  __    _    ____  _ 
|  \/  | ___ _ __ _ __ _   _  \ \/ /  \/  |  / \  / ___|| |
| |\/| |/ _ \ '__| '__| | | |  \  /| |\/| | / _ \ \___ \| |
| |  | |  __/ |  | |  | |_| |  /  \| |  | |/ ___ \ ___) |_|
|_|  |_|\___|_|  |_|   \__, | /_/\_\_|  |_/_/   \_\____/(_)
                       |___/                               

December 22, 2010

How to delete the last lines of a file

A friend of mine showed me a way to delete the last lines of a file after he read the article on how to delete the first lines of a file. The following is an example of how he did this with sed.

mike@shiner $ sed '$d' really_big_file.txt > new_file.txt

You'll need to use the single quotes to prevent the shell, such as bash, from interpreting $d as a variable. The '$' symbol matches the last line, similar to how it matches the end of the line in a regular expression. The 'd' tells sed that we want to delete the line.

Another way to do this, albeit not as elegant, is exemplified next.

mike@shiner $ tac really_big_file.txt | sed 1d | tac > new_file.txt

If you've never seen the tac command, it's similar to cat, but it's cat in reverse. I think it's kind of nifty that cat spelled backwards is tac. This helps with remembering the command.

Here's what I'm doing in each step:

1. cat the file in reverse.
2. Delete the first line.
3. cat the file in reverse again.
4. Save the output to 'new_file.txt'.

The end result is the same as before, but I can see someone arguing against it because of readability.

December 19, 2010

How to find files larger than X

You can use the following command to find files that are larger than 50M.

mike@shiner $ find . -type f -size +50000k

The -type argument tells find that we want to look at files and the -size argument specifies files larger than 50,000k. We can use the following command to get a nicely formatted output with the name of the file and the size.

mike@shiner $ find . -type f -size +50000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }' 

Alternatively, we can do the following to get the same output.

mike@shiner $ find . -type f -size +50000k | xargs ls -lh | awk '{ print $9 ": " $5 }' 

xargs is a handy command that takes each line of input and passes it to the proceeding command, which in this case is ls -lh.