0

I would like to find a way to get the unique keys that are used inside .rb and .yml files. These keys are used inside the hash ENV. So, there are files that contain things like:

ENV['key']

in multiple lines and at various positions within their lines. Also, those might appear multiple times within those lines.

So, If I have the file:

blah blah blah ENV['key1'] blah blah blah ENV['key2']
blah blah blah ENV['key2']
blah blah
ENV['key3'] blah blah ENV['key2']

then I would like to get the list:

key1
key2
key3

I have managed to do this:

find . -iname "*.rb" -o -iname "*.yml" | xargs egrep 'ENV\[.(.*).\]'

but I do not know how to actually get the keys.

Any help would be much appreciated.

1 Answer 1

0

Try using the -o flag to grep to get only the matching parts of the line:

find . '(' -iname "*.rb" -o -iname "*.yml" ')' -exec grep -o -E 'ENV\[.(.*).\]' {} + | sort -u | cut -d'[' -f 2 | tr -d "']"

Also, I highly recommend using the -exec flag to find instead of piping to xargs:

5
  • 1
    @jayhandren are you sure this one processes all files? I have tried that and works only with the ".yml" files. Does not process the ".rb" files. Nov 27, 2016 at 17:41
  • 1
    The logic on find is incorrect, and needs to instead be find . \( -iname "*.rb" -o -iname "*.yml" \) -exec ...
    – thrig
    Nov 27, 2016 at 17:46
  • thanks to both of you, corrected. @p.matsinopoulos it should work correctly now.
    – jayhendren
    Nov 27, 2016 at 18:02
  • I think it does not work if there are 2 or more occurrences of ENV inside the same line. Nov 27, 2016 at 20:11
  • @p.matsinopoulos it does work. if there are multiple matches on the same line, grep -o will print each match separately.
    – jayhendren
    Nov 28, 2016 at 14:33

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.