Find and replace to standardize whitespace
I have about 50 templates, and I would like to standardize whitespace on variables as follows --
Inputs: {{variable}}, {{ something }}, {{ test }}, etc.
Output: {{ varia开发者_如何学Goble }}, {{ something }}, {{ test }} # one space within inner bracket
How would I do this find and replace to all files within myproject/templates
? Thank you.
find /myproject/templates -type f | xargs sed -i 's/{{\s*\(\S*\)\s*}}/{{ \1 }}/g'
Translation:
find /myprojects/templates -type f
will find all items in /myproject/templates
that are regular files (as opposed to symlinks or directories).
xargs sed -i s/FIND/REPLACE/g'
will execute sed
to edit each file in place (that is, it will replace the contents of the file with the edited version). It will search for the pattern FIND
and replace it with REPLACE
globally (that is, everywhere it appears on the line).
The components of the FIND
pattern:
{{\s*
= two open-braces followed by zero or more whitespace characters
\(\S*\)
= any non-whitespace characters. (This means your variable names cannot contain internal spaces.) The escaped parens will save those characters (which are your variable names) for use in the REPLACE
pattern.
\s*}}
= zero or more whitespace characters followed by two close-braces.
The components of the REPLACE
pattern are two open-braces, a single space, the variable name we saved using \(\S*\)
, another space, and the two close-braces.
Hope that helps!
精彩评论