January 15, 2011

How to sum up the values in a file

Once you know how to remove a column from a file, then a time will come where you'll want to sum up the values in a column. For this example, let's take a look at a file with numbers in it.

mike@shiner $ cat file-with-numbers

We can sum up the values in this file with the following command.

mike@shiner $ cat file-with-numbers | awk '{sum+=$1}END{print sum}'

We can see here that the sum of the numbers in the file total to 21.

January 13, 2011

How to remove spaces from filenames

I often run into files with spaces in them and I want to rename them. Once again, there's a command that's appropriately named to do the job. I'm going to go over how to use the rename command. Let's take a look at the files we're going to work with.

mike@shiner $ ls
foo bar.txt  test this.txt

We have two files which are named 'foo bar.txt' and 'test this.txt'. We're going to use the following command to get rid of the spaces.

mike@shiner $ rename 's/ /_/' *.txt

The command takes two arguments. The first argument is a regular expression where the 's' stands for substitute. The contents between the first set of slashes represent what we're matching on. The '_' between the second set of slashes represent what we want to replace it with. The second argument, *.txt, tells rename what files will be affected. The preceding command happily renders the following result.

mike@shiner $ ls
foo_bar.txt  test_this.txt

Now let's say we want to replace the underscores with dashes. We can do this with the following command.

mike@shiner $ rename 's/_/-/' *.txt
mike@shiner $ ls
foo-bar.txt  test-this.txt

January 3, 2011

How to pipe STDOUT to vim

I usually use ColorDiff when I want to get a colorized diff from the command line.

mike@shiner $ cvs diff -up | colordiff

I was talking with a friend about vim and he showed me how to utilize vim for a similar purpose.

mike@shiner $ cvs diff -up | vim -

This is great because it gives you the same syntax highlighting benefits, but you don't have to install another application.