Reputation: 83
I am using bash
perl
and sed
to take GraphQL queries and convert them to TypeScript types. I have it all figured out except one piece - I cannot figure out how to insert a comma at the end of each line within a regex match.
This is the raw *.graphqls
text that I'm successfully matching:
enum ContentType {
LESSON
WARMUP
QUIZ
PROJECT
}
The Regex that makes the match (selects everything between and including enum
and }
):
s/(?s)(?=enum).*?(})
I can easily replace this entire segment with bash
and perl
:
ENUM_MATCH="s/(?s)(?=enum).*?(})/replacement/"
perl -i -0pe "${ENUM_MATCH}" "${FULL_PATH}"
But what I need to do is replace this enum text with the same text, except with a comma on each enum line item - end result would look like this:
enum ContentType {
LESSON,
WARMUP,
QUIZ,
PROJECT
}
Upvotes: 0
Views: 373
Reputation: 66881
If a trailing comma (after PROJECT
) is allowed, which is legal as of C99 and C++11
perl -i -pe'if ($r = /^\s*enum/ .. /}\s*$/) { s/$/,/ if $r!=1 && $r!~/E0$/ }' file
This uses range operator, and its return with which to exclude its first and last line.
Upvotes: 1
Reputation: 385897
With trailing comma:
s{enum[^{]*\{\K([^}]*)}{ $1 =~ s/\n/,\n/gr }seg
Without:
s{enum[^{]*\{\K([^}]*)}{ $1 =~ s/\n/,\n/gr =~ s/,(?=[^,]*\z// }seg
Upvotes: 0
Reputation: 7499
If ,
is allowed after PROJECT
:
awk '$1=="}"{f=0} f{$0=$0 ","} $1=="enum"{f=1} 1' data
Upvotes: 0
Reputation: 195089
an awk one-liner works for your example:
awk '/enum .*\{/{print;next}p{print p (/\}/?"":",")}{p=$0}END{print p}' file
Upvotes: 0