Tuesday, December 14, 2010

String matching in a file using (sed/grep) commands in LINUX

SED command using & for match string:
The special character "&" corresponds to the pattern found.
Suppose the filename ch.txt contains following lines.  And we want for each function name to add (* ) brackets .
xpcom_ProcessNextEvent(int state); 
loc_wer_test(int state);
Following command converts content in ch.txt into following format and stored output in ch1.txt file.
$sed 's/[a-zA-Z]*_*[a-zA-Z]*_*[a-zA-Z]*(/int (*&)/' < ch.txt >  ch1.txt
The Output of above command in ch1.txt file is as per follows:
int (*xpcom_ProcessNextEvent()int state); 
int (*loc_wer_test()int state);


Now we want to swap "()" bracket with ")(" from the output of above command. Following commands does that job.
$sed 's/()/)(/'  < ch1.txt > ch2.txt
int (*xpcom_ProcessNextEvent)(int state); 
int (*loc_wer_test)(int state);

You could also double a pattern, e.g. the first number of a line:
$ echo "123 abc" | sed 's/[0-9]*/& &/'
123 123 abc
In above command "123 abc" was input and output was "123 123 abc".
You can have any number of "&" in the replacement string.

GREP command to copy a matching string line from a file to another file.
Suppose input_filename contains following:
 //Escape() Function hook
  int js_js_str_fun (...)
 {
    .....
  }
int js_str_fun2 (...)
{
    .....
 }

Using following command we can extract a line with function name:
$grep "int .*(.*)"  input_filename > output_filename

Above commands stores following output in output_filename file:
  int js_js_str_fun (...)
int js_str_fun2 (...)

1 comment:

  1. @Akhil: Thanks for providing useful links on Find and Awk command.

    ReplyDelete