Saturday, July 14, 2007

Your favourite Unix One-Liners

Recursively List only directories in current directory courtesy

  • find . -type d -print
The most typical options for -type are as following:
  • d -Directory
  • f - File
  • l - Link


Displaying useful information in the shell prompt:

  • export PS1=[${LOGNAME}@$(hostname)]'$PWD>' # [rakou@unixbox]\usr\local\bin>
  • export PS1=${LOGNAME}@$(hostname)':'`pwd`'>' #tested to work on zsh
  • export PS1='\t \u@\h \w $ ' # for bash lovers
Find and replace all occurrences of some text in all the files in current directory.

  • find ./ -type f -exec sed -i 's/find/replace/' {} \;
List only directories

  • ls -l grep '^d' awk '{print $8}' # In my case $8 was the directory name returned by ls command which may be $9 in your case (It depends on the flavor of linux/unix you are using)


Copy particular files to a directory using find command courtesy

A final cool usage of find is to incorporate it into another command such as "cp". For example in the following command, we copy all .bak files found by find, to the "Backup" directory

  • cp `find . -name '*.bak' -print`

In this case, the use of back ticks (`) allows us to substitute the results of the command into the rest of the line.