Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have about 100 print statements in a file like this:

printf("%f \n\n",row1.req_pnttime);

I want to copy the variable name inside the string so that it becomes like this

printf("row1.req_pnttime: %f \n\n",row1.req_pnttime);

Can anyone help me do this?

PS-The length of the variable name is different for every print statement so I need a generic way to do this.

share|improve this question

1 Answer 1

up vote 6 down vote accepted
sed 's/\(.*("\)\(.*,\)\(.*\))/\1\3: \2\3)/' /path/to/input.txt >/path/to/output.txt

Explanation

  • The general format is sed 's/find/replace/'. i.e. find an expression and replace it.
  • \( ... \) these are capturing groups. So anything that matches in between them is "captured" in a variable and can be recalled in the replace part, with \1, \2, \3, etc.
  • So here, find \(.*("\)\(.*,\)\(.*\)).
    • Capturing group 1: .*(". Capture from the beginning to anything that ends with ("
    • Capturing group 2: .*,. From #1, capture up to ,.
    • Capturing group 3: .*. Capture up to (but not including) ).
  • Then replace with the capturing groups and additional formatting \1\3: \2\3).
share|improve this answer
1  
+1 for explanation. –  Avinash Raj Apr 7 at 15:23
    
Great explanation. Thanks. –  Vivek V K Apr 7 at 16:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.