Home > Blockchain >  How to apply my sed command on the files resulting from grep filtering only
How to apply my sed command on the files resulting from grep filtering only

Time:04-28

I have crafted this sed command which looks to be working fine, only it's being applied to all the files in my directory :

find . -type f -name '*.js' -not -path './node_modules/*' -exec sed -i .bak -E '
1i\
const env = require('\''env-var'\'');
s/(^|[^[:alnum:]_])process\.env\.([[:alnum:]_] ) \|\| ([[:alnum:]_] )($|[^[:alnum:]_])/\1env.get('\''\2'\'').default('\''\3'\'')\4/g
s/(^|[^[:alnum:]_])process\.env\.([[:alnum:]_] )($|[^[:alnum:]_])/\1env.get('\''\2'\'')\3/g
' {} \;

I wish to apply those transformations only to the files which match this grep command :

grep -r "process\.env\." --exclude-dir=node_modules

I tried using the pipe but I can't make the two working together. What's the right way to handle it?

EDIT: I tried this

➜  app-service git:(chore/adding-env-example) ✗ grep -r "process\.env\." --exclude-dir=node_modules | sed -i .bak -E '
1i\
const env = require('\''env-var'\'');
s/(^|[^[:alnum:]_])process\.env\.([[:alnum:]_] ) \|\| ([[:alnum:]_] )($|[^[:alnum:]_])/\1env.get('\''\2'\'').default('\''\3'\'')\4/g
s/(^|[^[:alnum:]_])process\.env\.([[:alnum:]_] )($|[^[:alnum:]_])/\1env.get('\''\2'\'')\3/g
' {} \;

sed: {}: No such file or directory

I want only the files containing process.env.SOMETHING to be edited.

CodePudding user response:

Work with pipes. xargs comes handy:

find ... -print |
   xargs -d '\n' grep -l 'regex' |
   xargs -d '\n' sed 'stuff'

CodePudding user response:

Suggesting to reverse order of commands. sed on filtered list of files.

Files filter is combination of grep filter on find filter: grep -l "process\.env\." $(find . -type f -name '*.js' -not -path './node_modules/*').

 sed -i .bak -E '
1i\
const env = require('\''env-var'\'');
s/(^|[^[:alnum:]_])process\.env\.([[:alnum:]_] ) \|\| ([[:alnum:]_] )($|[^[:alnum:]_])/\1env.get('\''\2'\'').default('\''\3'\'')\4/g
s/(^|[^[:alnum:]_])process\.env\.([[:alnum:]_] )($|[^[:alnum:]_])/\1env.get('\''\2'\'')\3/g
' $(grep -l "process\.env\." $(find . -type f -name '*.js' -not -path './node_modules/*'))

   
  • Related