Home > Enterprise >  How to grep cloud functions in a multiline format separated by comma?
How to grep cloud functions in a multiline format separated by comma?

Time:04-22

I have been trying to fetch the cloud functions using grep/awk/sed however the current command is not fetching the cloud functions listed in a multiline format.

This is the current command that is being passed as a variable during runtime:

deploy.sh

functions_list=$(grep 'export' src/index.ts | awk -F '[}{]' '{print $2}' | sed 's/^ *//; s/ *\$//; /^\$/d' | grep -v somefunction || echo '')

index.ts

export { functionA } from './functions';
export { functionB } from './functions';
export {
    functionC,
    functionD,
    functionE
} from './functions';
export { functionF } from './functions';
export { functionG } from './functions';

Then the output will be like this:

functionA
functionB

functionF
functionG

Anyone who has any idea on how to have the output to be like this instead?

functionA
functionB
functionC
functionD
functionE
functionF
functionG

CodePudding user response:

See final command:

functions_list=$(awk 1 ORS=' ' src/index.ts | sed -e 's/    / /g ; s/;/\n/g' | awk -F '[}{]' '{print $2}' | sed 's/^ *//; s/ *\$//; /^\$/d; s/,  /\n/g' | grep -v somefunction || echo '')

awk reads/scans input line by line; hence skips the functionC, functionD and functionE as they do not fall under the provided pattern:

'[}{]' '{print $2}'

I've added awk/sed commands to initially replace new line with whitespaces.

awk 1 ORS=' ' src/index.ts | sed -e 's/    / /g ; s/;/\n/g'

Then, finally, to replace commas with newline.

s/,  /\n/g

CodePudding user response:

The parsing here is very brittle. Without complicating things too much, try switching to Perl, which lets you examine the whole input file in one go.

perl -n0777 -e 'while (m/export \{([^{}] )\}/mg) {
  $s = $1; print "$1\n" while $s =~ m/(\w )/mg }' src/index.ts

The first regex loops over the export { ... } expressions and pulls out the text between the braces. The second picks out the symbols, skipping any whitespace or punctuation, and prints them.

  • Related