1

I'm trying to use find + sed/awk to replace this string:

main(argc, argv)
int argc;
char *argv[];
{

with:

int main(int argc, char *argv[])
{

Does anyone know how to do this?

Many thanks!

James
  • 65
  • 1
  • 5
  • did you want the solution only in sed? – Avinash Raj Aug 29 '14 at 12:49
  • If possible - I can then use find + sed to replace in a large number of files. – James Aug 29 '14 at 12:50
  • If you get a solution in `awk`, couldn't you use `find + awk` just as well? – Barmar Aug 29 '14 at 12:51
  • Oh sure - I assumed I'd need to use sed. – James Aug 29 '14 at 12:52
  • Thanks - no solution was given for that question. I only need to convert the main functions. – James Aug 29 '14 at 13:00
  • You should use Perl instead of sed. sed is not really made for multiline replacement. – nowox Aug 29 '14 at 13:42
  • @James ping! Just to know if you find another way of if my answer helped you or not. – Tensibai Sep 03 '14 at 09:14
  • **Example (gets rid of all newlines in `ls -l` output): `ls -l | nawk -v RS='' '{ gsub(/\n/, " "); print }'`** – Andrew Sep 13 '17 at 17:45
  • Brief explanation: | pipes the output of `ls` to `nawk`, `nawk` is `awk` but for advanced string processing (there's also a similar `gawk`), `-v RS=''` sets the "record separator" to empty so that it processes the entire input all at once instead of one line at a time (default), `'{ print }'` by itself would just print all of the input, but then the `'gsub(/search regex/', "replace string");` before it performs your actual multiline regex replacement! :) – Andrew Sep 13 '17 at 17:48

1 Answers1

1
cat test.txt
  main(argc, argv)
  int argc;
  char *argv[];
  {

with this awk it produce the desired output:

cat test.txt | awk  'BEGIN { args=""; nb=0; }; /main\(argc, argv\)/,/\{/ { if (!/^(main|\{).*$/) { tmp=$0; sub(/;/,"",tmp); if (nb) { args=(args "," tmp); nb+=1; } else { args=tmp; nb+=1;} };} END { print "main(" args ")\n{\n"; }'

Output:

main(int argc,char *argv[])
{

Details on the awk part:

BEGIN { args=""; nb=0; }; # Init Variables
 /(main\()argc, argv\)/,/\{/ { # for lines matching 'main' to line matching '{'
   if (!/^(main|\{).*$/) {  # if we're not on the main or { line
     tmp=$0; # copy the match
     sub(/;/,"",tmp); # remove the trailing ;
     if (nb) { # if we're not on the first arg, concat with preceding separed by ,
       args=(args "," tmp); 
       nb+=1; 
     } else { # it is the first arg, just assign
       args=tmp; 
       nb+=1;
     } 
   };
 } 
END { print "main(" args ")\n{\n"; } # we finished matching, print the result.

This is just on your exemple, if you need something more complex you should be able to use a match group and $1 $2 for the function name if needed.

Edit: I let you extend it for you particular needs in replacement within files.

Tensibai
  • 15,557
  • 1
  • 37
  • 57