Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 6 down vote accepted
sed 's/\(.*("\)\(.*,\)\(.*\))/\1\3: \2\3)/' /path/to/input.txt >/path/to/output.txt


  • 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 for explanation. – Avinash Raj Apr 7 '14 at 15:23
Great explanation. Thanks. – Vivek V K Apr 7 '14 at 16:32

Your Answer


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.