1

I do have several source code files (.cpp) containing the following line:

other stuff
...
TRACE(arg1, arg2, ...);
...
other stuff

where arg1, arg2, ... denote arbitrary function call arguments separated by a comma and possibly preceded by a whitespace.

The goal is to parse each line in each source file in my project and remove the first argument (arg1) from the function call TRACE, such as

TRACE(arg2, arg3, ...);

Note that function TRACE can be preceded by an arbitrary number of whitespace and can itself contain the string TRACE such as

TRACE(0, TRACE_INFO, "Test ");
    TRACE(  0 , TRACE, 4,5 ,6);

Is there an easy way to do so ?

A test file test.cpp contains:

   TRACE( "I2Ccontrol::I2Ccontrol", TRACE_FATAL,0);

3 White spaces, no preceding lines no following lines

1 Answer 1

3

Using sed with extended regex:

sed -r 's/(\bTRACE\()([^",]+,\s*|\s*"[^"]*"\s*,\s*)(.*\);)/\1\3/' file

To change the file in-place use sed --in-place -r ...

EDIT:

Testing input from comment:

echo '   TRACE( "I2Ccontrol::I2Ccontrol", TRACE_FATAL,0);' |sed -r 's/(\bTRACE\()([^",]+,\s*|\s*"[^"]*"\s*,\s*)(.*\);)/\1\3/'
#three white space before TRACE

Output:

   TRACE(TRACE_FATAL,0);
Sign up to request clarification or add additional context in comments.

18 Comments

Great. This solution supports even commas in the value of arg1.
Thanks a lot! will this also work (in place) for multiple files like: sed --in-place -r ... file1 file2 ... ?
But wont there be a whitespace left over after each bracket now ? Such as TRACE( arg2,...
True just consistency in coding style. I have one Issue left though: A function call could look like this: TRACE(0, TRACE_INFO, "Test ", ... This would not only remove the 0 but also arg2 in this case TRACE_INFO which is certainly a real issue
Doesn't work. Content of test.cpp: TRACE( "I2Ccontrol::I2Ccontrol", TRACE_FATAL,0); (preceeded with 3 whitespaces) The following command sed --in-place -r 's/(\bTRACE()([^",]+,\s*|\s*"[^"]*",\s*)(.*);)/\1\3/' test.cpp doesnt affect the file test.cpp at all
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.