3

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.

1 Answer 1

9
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).
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .