Tuesday, June 19, 2012

How to find and replace a string in multiple files

To find and replace a tag across multiple files from command-line in linux, consider this simple shell script:
#!/bin/sh  
today=`date -R`
find . -type f \( -name "*.h" -o -name "*.cpp" \) -print | \
   xargs sed -i 's/{DATE}/'"$today"'"/g'

We scan for regular C++ header and source files. We then pipe the list of files found into 'sed' editor that does line-by-line search and replace.

The only non-trivial part here is the replacement string, '"$today"'. The inside double quotes are needed to let shell expand $today to its value.

Wednesday, June 13, 2012

How to insert spaces with Tab key with Vim

Some projects require for one reason or another to use spaces instead of a Tab character to indent the C/C++ code. Most of the time it is related to the diffs that are generated by the CM systems. If you are a Vim user, you can configure your editor to insert spaces with Tab keystroke by adding these commands to your ~/.vimrc:

 set ts=4  
 set shiftwidth=4  
 set expandtab  
 set nowrap  

This assumes that the width of desired tab is 4 characters. gVim is a popular GUI font-end for Vim editor. However, I found the way gVim stores its configuration into ~/.vimrc non-intuitive:
  • Go to your $HOME directory.
  • Start the shell terminal.
  • Start gvim from command-line.
  • Configure your settings the way you like them to be.
  • Save the setting to .vimrc with command
     :mkvimrc  
    
The trick here is to run gvim from your home directory. Otherwise, gVim writes .vimrc file in the current directory where it was started from.

Monday, May 28, 2012

How to create a source tree patch with GNU diff/patch

First, make a copy of your source tree:

  $ cp -R libfoo.orig/ libfoo.new/

When you finished with modifications to libfoo.new/, generate GNU unified patch:

  $ diff -rupN libfoo.orig/ libfoo.new/ > libfoo-05282012.patch

To generate a unified patch against the CVS:

  $ cvs diff -u > libfoo-05282012.patch

The patch can be applied to the origianl source tree:

  $ cd libfoo/
  $ patch -p0 < libfoo-05282012.patch

To revert the patch:

  $ patch -p0 -R < libfoo-05282012.patch