Wednesday, January 12, 2011

Wonders of shell command

It is often said that there is never any justification for things being complex when they could be simple. Most of the time we spend a lot of effort trying to a complete a task which in fact can be accomplished by a single stroke in the command line. For instance, to remove all the empty files in a graphical environment, you have to go through the search options, select the files and finally delete them. Whilst if you working on a terminal the same task can be done via a single command.
Generally when we talk about command line, we start relating command-line stuff with geek stuffs which is not true. All I am saying is that, it is worth trying to learn a few commands if it saves your time and reduces complexities.
So, if you go through this article, you will eventually appreciate the wonders of the shell commands.

1. Extract specific field from a colon delimited file and save it to another file
# cut -d: -f 2,5 sourcefile.txt > targetfile.txt
This is really useful when the source file has hundreds of lines.

2. Sort a file in ascending order removing duplicate entries and save the result to a file
# sort -u -o target.txt sourcefile.txt

3. Sort specific field from a colon delimited file removing duplicate entries and save the result to a file
# sort -t: -u -k 2 -o target.txt sourcefile.txt ( to sort in descending order use -r option )

4. Display the largest file (in size) of the current directory.
# du -s * | sort -nr | head -1
or
# ls -al | sort -nr -k5 | head -1
( to display top 5 largest files in size, use: head -5 )

5. Combine two files and save the result in a file

Read more: Fortystones