0

I have a file with

<vcell i="2" v="2" s="0" m="0"/>
<cell i="3" v="3187"/>
<cell i="4" v="1"/>
<cell i="5" v="17"/>
<cell i="6" v="0"/>
<cell i="7" v="2"/>
<cell i="8" v="17"/>
<cell i="9" v="0 / 13"/>

I need to replace in

<vcelli2 v="2" s="0" m="0"/>
<celli3 v="3187"/>
<celli4 v="1"/>
<celli5 v="17"/>
<celli6 v="0"/>
<celli7 v="2"/>
<celli8 v="17"/>
<celli9 v="0 / 13"/>

I can do this with a sed and regular expression?

1

Yes, it can be done with a sed command.

Remember to backup the file before making any changes to it. The backup can be removed after confirming that the results are correct or kept for later.

As for the sed command, something like

sed -i.backup -E 's/ i="([0-9]*)"/i\1/g' file

should work (note that this will automatically make a backup of the original file, remove the backup part if done manually).

The -i flag (not available in all flavours of sed) stands for in-place (i.e. save back to the original file; keep copy of original with extension .backup) and -E (extended regex) is used to avoid escaping the parentheses.

  • Not all portability issues have been resolved. There is simply no portable way to give an empty value to -i that works in all seds. The alternative that you propose will leave an additional file in the directory. The only truly portable solution for a no additional file left is a two step tango: sed -E 's/ i="([0-9]*)"/i\1/g' file >newfile; mv newfile file @Philippos – Isaac Oct 15 '19 at 18:35
  • 1
    @Isaac Well, there is a reason for some implementations forcing the user to keep a backup. I‘ve already shot myself in the foot, so keeping a backup seems to be a good idea to me. Btw, I would always prefer sed ... && mv ... over the semicolon version to avoid overwriting my source with an empty file in case of an error. – Philippos Oct 15 '19 at 19:26
  • I completely agree in that it is always a good idea to keep a backup. But that is an issue which is orthogonal to a solution being portable. There is no portable solution for no additional file (-i receiving an empty value). @Philippos – Isaac Oct 15 '19 at 21:41
  • 1
    The most reliable solution, IMhO, is to make a copy of the original (cp original backup), do all modifications to a second file (sed '…' original > result), and, then, after all heavy processing has been done, do cat result > original and rm result. That way you get to keep a backup, the result file keeps the symbolic links (if any), permissions and inode number of the original. But that has the cost of (short lived) additional disk space. That shouldn't be an important issue in most cases. @Philippos – Isaac Oct 15 '19 at 21:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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