bergercookie
bergercookie

Reputation: 2790

Find and replace surounding of a string in file

There are many occurrences of the following command in a Latex file:

\en{some_string}

This is a custom command for entering English text. Now I want in each of these commands to delete the surroundings so that:

\en{some_string} ---> some_string.

How can I implement it using a bash or vim command?

Upvotes: 0

Views: 86

Answers (2)

xvedar
xvedar

Reputation: 26

vim regex to substitute all the lines in a file:

:%s/^\\en{\([0-9a-zA-Z_]*\)}/\1/

Upvotes: 0

buff
buff

Reputation: 2053

You can use sed command as following:

sed --in-place=.bak 's/\\en{\([^}]*\)}/\1/g' your_file

This creates backup of your original file under .bak extension. Then it replaces all the the occurences in the file specified.

  • s/original/replace/g replaces all occurences of original with replace
  • \(...\) captures the match between to \1 which is applied on the right side
  • [^}]* matches any number of characters other than }
  • \\en{\([^}]*\)} i.e. the full left hand side therefore matches the \en{some_string} pattern and stores what's between { and } to
  • \1 which is used as a replacement on the right hand side.

You can apply the exact same command also in vim:

vim your_file
:%s/\\en{\([^}]*\)}/\1/g

Here : switches to command line mode, % means a range of all lines of the file, the rest is the same.

Upvotes: 4

Related Questions