Edit lines in file preserving part of it

Hello:
I have the following HTML table:

<table>
    <thead>
        <tr>
            <th>Code</th>
            <th>Percentage</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>30%</td>
        </tr>
        <tr>
            <td>2</td>
            <td>70%</td>
        </tr>
    </tbody>
 </table>

I would like to add a button with an event to every <td> element with a code, like the following:

<table>
    <thead>
        <tr>
            <th>Code</th>
            <th>Percentage</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><button onclick="reset(1)">Reset</button>1</td>
            <td>30%</td>
        </tr>
        <tr>
            <td><button onclick="reset(2)"></button>2</td>
            <td>70%</td>
        </tr>
    </tbody>
 </table>

Note that I'm not asking how to parse the HTML. Instead, I would like to know how to replace every \t\t\t<td>x</td> line by \t\t\t<td><button onclick="reset(x)">x</button></td> , where x is the code number.

I need to do it with a command-line text editor without input from the user, because I have many files like this one and my idea is to edit all of them using find with the -exec option.

This would be a simple task with ex or ed if I just had to replace the same concurrence. But in this case, I need to keep the code in every replacement. That's what I'm struggling with. I'm afraid I'll need advanced tools like awk and I honestly don't know how to do it.

How can I add the button with the event to the table cells?
Thanks in advance.

Hi, with sed you can try:

sed 's|<td>\([0-9]\{1,\}\)</td>|<td><button onclick="reset(\1)">Reset</button>\1</td>|' file

You can add the leading tabs if you need them, but in the sample there were none so I left them out...
The part in red is a subexpression in escaped parentheses plus the back references to it in the replacement part...

2 Likes

This is exactly what I needed, Scrutinizer. Thank you very much! The tabs don't seem to be altered with the command you provided, so I don't think I'll need to add them.

One last question. I'm using GNU sed . Can I safely use the -i option with the replacement command you wrote to do in-place editing?

You are welcome Cacializ. GNU sed -i has a backup option:

-i[SUFFIX], --in-place[=SUFFIX]

The BSD sed man page says you should always use it. Anyway in general it is always a good idea to have backups and stuff like this would be best to put in a git repository and then you can just checkout the original files if something goes wrong..

1 Like