Class JRT
- Direct Known Subclasses:
SandboxedJRT
Variable access is achieved through the VariableManager interface. The constructor requires a VariableManager instance (which, in this case, is the compiled Jawk class itself).
Main services include:
- File and command output redirection via print(f).
- File and command input redirection via getline.
- Most built-in AWK functions, such as system(), sprintf(), etc.
- Automatic AWK type conversion routines.
- IO management for input rule processing.
- Random number engine management.
- Input field ($0, $1, ...) management.
All static and non-static service methods should be package-private
to the resultant AWK script class rather than public. However,
the resultant script class is not in the io.jawk.jrt package
by default, and the user may reassign the resultant script class
to another package. Therefore, all accessed methods are public.
- Author:
- Danny Daglas
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionJRT(VariableManager vm, Locale locale, AwkSink awkSink, PrintStream error) Create a JRT with explicit default output and error streams. -
Method Summary
Modifier and TypeMethodDescriptionbooleanadvanceToNextFile(InputSource source) Advance the main input to the next input file, applying pendingname=valuecommand-line assignments along the way.voidapplyRS.booleanapplySpecialVariable(String name, Object value) Applies the assignment of a single JRT-managed special variable.final voidapplySpecialVariables(Map<String, Object> variableMap) Applies only the JRT-managed special variable assignments from the supplied map (FS, RS, OFS, ORS, CONVFMT, OFMT, SUBSEP, FILENAME, NF, NR, FNR, ARGC, IGNORECASE).static voidCalled by AVM/compiled modules to assign local environment variables to an associative array (in this case, to ENVIRON).final voidassignInitialVariables(Map<String, Object> initialVarMap) Assign all -v variables.caseAwarePattern(Pattern pattern) Returns the pattern itself, or its case-insensitive twin whenIGNORECASEis set.static booleanCompares two objects.static booleanCompares two objects likecompare2(Object, Object, int), folding case in string comparisons whenignoreCaseis set: gawk'sIGNORECASEapplies to string relational operators, not only to regexp operations.booleanconsumeCurrentFileInput(InputSource source) Attempt to consume one record from the current input file only, without ever advancing to the next input file.Attempt to consume one record of the current input file only forgetline target, returning the input value and leaving the current input record state untouched.booleanconsumeInput(InputSource source) Attempt to consume one record from a structured input source and expose it as the current input record.booleanconsumeInputForEval(InputSource source) Consume at most one record from a structured source for expression evaluation.consumeInputToTarget(InputSource source) Attempt to consume one record from a structured input source forgetline target, returning the input value and leaving the current input record state untouched.static booleancontainsAwkKey(Map<Object, Object> map, Object key) Checks key existence using AWK semantics when the supplied map is backed by anAssocArray, otherwise falling back to regularMapsemantics.copySpecialVariables(Map<String, Object> variableMap) Copies only the JRT-managed special variables from the supplied map.createAwkMap(boolean sortedArrayKeys) Creates an AWK-managed associative array and exposes it as a plainMapfor callers that do not need the concrete runtime type.static ObjectReturn an object which is numerically equivalent to one minus a given object.dynamicPattern(String ere) Compiles a dynamic (string) regexp with the flags implied by the currentIGNORECASEsetting, caching compiled patterns by expression text: dynamic regexps are typically reused across records (for example agsub(dynstr, ...)loop), and the JDK'sPattern.compile(String, int)reparses the expression on every call.Get ARGC from the VariableManager.Get ARGIND as tracked by JRT.static ObjectgetAssocArrayValue(Map<Object, Object> map, Object key) Reads a map element using AWK semantics when the supplied map is backed by anAssocArray.Returns the default output sink used byprintandprintf.getAwkStringEntry(Map<Object, Object> map, Object key) Returns the AWK string value of an associative array entry, ornullwhen the array has no such key.Returns the current CONVFMT value as a string.Get CONVFMT from the VariableManager.getERRNO()Get ERRNO as tracked by JRT.protected AwkSinkgetFileAwkSink(String fileNameParam, boolean append) Resolves the sink used by file redirection.Get FILENAME as tracked by JRT.getFNR()Get the current FNR value as tracked by JRT.Returns the current FS value as a string.getFSVar()Get FS from the VariableManager.Get IGNORECASE from the VariableManager.Getter for the fieldinputLine.Returns the locale used for number formatting in this runtime.getNF()Retrieve the current value of NF.getNR()Get the current NR value as tracked by JRT.Get OFMT from the VariableManager.Returns the current OFS value as a string.Get OFS from the VariableManager.Returns the current ORS value as a string.Get ORS from the VariableManager.Getter for the fieldoutputFiles.Returns the underlyingPartitioningReadercurrently in use by the activeInputSource, ornullif the source is not stream-based.protected AwkSinkgetPipeAwkSink(String cmd) Resolves the sink used by pipe redirection.Returns the text produced by the lastreplaceFirst(java.lang.String, java.lang.String, java.lang.String)orreplaceAll(java.lang.String, java.lang.String, java.lang.String)call.Get RLENGTH tracked by JRT.Returns the current RS value as a string.Get RSTART tracked by JRT (1-based).getRSVar()Get RS from the VariableManager.Returns the current SUBSEP value as a string.Get SUBSEP from the VariableManager.booleanbooleanhasPendingInputFileError(InputSource source) Returns whether the current input file of the given source failed to open, leaving a pending error that only anextfilestatement in a BEGINFILE rule may bypass.static ObjectReturn an object which is numerically equivalent to one plus a given object.intImplements theindex()builtin: the 1-based position ofneedlewithinhaystack, or 0 when absent, folding case whenIGNORECASEis set.protected voidinitializeInputFields(String record, List<String> preFields) Initialize$0..$NFfrom a pre-split field list.static booleanisActuallyLong(double d) Determines whether a double value actually represents a long integer within the limits of floating point precision.static booleanReturns whether the name is a gawk-only special variable that POSIX mode treats as an ordinary identifier, likegawk --posixdoes.booleanReturns whether IGNORECASE is currently nonzero, making regexp operations case-insensitive.static booleanReturns whether the supplied variable name is managed directly by JRT rather than through the AVM runtime stack.booleanisParseableNumber(String value) Returns whether the supplied text parses as an AWK number under this runtime's locale, as used for strnum recognition.Attempt to close an open stream, whether it is an input file, output file, input process, or output process.voidjrtCloseAll.booleanjrtConsumeCommandInput.jrtConsumeCommandInputForGetline(String cmdString) Retrieve the next line of output from a command, executing the command if necessary and store it to $0.booleanjrtConsumeFileInput(String fileNameParam) jrtConsumeFileInput.jrtConsumeFileInputForGetline(String fileNameParam) jrtConsumeFileInputForGetline.jrtGetInputField(long fieldnum) jrtGetInputField.jrtGetInputField(Object fieldnumObj) Retrieve the contents of a particular input field.Retrieve $0.jrtGetPrintStream(String fileNameParam, boolean append) Retrieve the PrintStream which writes to a particular file, creating the PrintStream if necessary.voidSplits $0 into $1, $2, etc.jrtSetInputField(Object valueObj, long fieldNum) Stores value_obj into an input field.voidAdjust the current input field list and $0 when NF is updated by the AWK script.jrtSpawnForOutput(String cmd) Retrieve the PrintStream which shuttles data to stdin for a process, executing the process if necessary.Executes the command specified by cmd and waits for termination, returning an Integer object containing the return code.booleanEvaluates the AWK match operator (text ~ regexp), honoringIGNORECASEfor both precompiled regexp constants and dynamic expressions.intmatchPosition(String s, String ere) match()functionality: locatesereinshonoringIGNORECASE, updatingRSTARTandRLENGTH.static BSDRandomnewRandom(int seed) newRandom.static longparseFieldNumber(Object obj) Convert a field designator to a non-negative long, raising an AWK runtime exception when the value is invalid.voidprepareForExecution(String defaultFs, String defaultRs) Resets per-execution JRT state and re-applies the default runtime special variables for a new script or expression execution.static StringprepareReplacement(String awkRepl, boolean backreferences) Converts an AWK replacement text into a JavaMatcherreplacement:&becomes the whole match,\&a literal ampersand, and$is escaped.static StringprepareReplacement(String awkRepl, int maxGroup) Converts an AWK replacement text into a JavaMatcherreplacement, resolving gensub-style backreferences against a known number of capture groups:\NbeyondmaxGroupis replaced by the empty string, as gawk does, instead of producing a group reference that would make the matcher throw.voidprintDefault(Object[] values) Writes a standard AWKprintoperation to the default output.voidprintfDefault(String format, Object[] values) Writes a formatted AWK output string to the specified sink.static voidprintfNoCatch(PrintStream ps, Locale locale, String fmtArg, Object... arr) printfFunctionNoCatch.static voidprintfNoCatch(Locale locale, String fmtArg, Object... arr) printfFunctionNoCatch.voidprintfToFile(String fileNameParam, boolean append, String format, Object[] values) Writes formatted AWK output to a redirected file.voidprintfToProcess(String cmd, String format, Object[] values) Writes formatted AWK output to a redirected process.voidprintToFile(String fileNameParam, boolean append, Object[] values) Writes a standard AWKprintoperation to a redirected file.voidprintToProcess(String cmd, Object[] values) Writes a standard AWKprintoperation to a redirected process.voidprintWarning(String message) Prints a runtime warning message to the warning stream (stderr by default), mirroring where gawk sends its diagnostics.protected voidintReturns thePatternflags implied by the currentIGNORECASEsetting; dynamic regexps should be compiled with these flags.intreplaceAll(String orig, String repl, String ere) gsub()functionality: replaces every match ofereinorigwithrepl, honoringIGNORECASE.intreplaceFirst(String orig, String repl, String ere) sub()functionality: replaces the first match ofereinorigwithrepl, honoringIGNORECASE.voidSet ARGC via the VariableManager.voidSet ARGIND tracked by JRT.voidsetAwkSink(AwkSink sink) Sets the sink used by defaultprintandprintfoperations.voidsetCONVFMT(Object value) Set CONVFMT via the VariableManager.voidSet ERRNO tracked by JRT.voidsetErrorStream(PrintStream errorStream) Sets the stream used for the stderr output of spawned processes (e.g.system("...")).voidsetFILENAMEViaJrt(Object name) Set FILENAME through VariableManager and update JRT mirror.voidAssign FNR to a specific value; also updates the VariableManager copy.voidSet FS via the VariableManager.voidsetIGNORECASE(Object value) Sets IGNORECASE, precomputing its truth value so regexp operations can test a boolean instead of coercing the raw value on every match.voidsetInputLine(Object inputLineParam) Setter for the fieldinputLine.voidSet NF to the specified value and update $0 and fields accordingly.voidAssign NR to a specific value; also updates the VariableManager copy.voidSet OFMT via the VariableManager.voidSet OFS via the VariableManager.voidSet ORS via the VariableManager.voidsetRLENGTH(Object value) Set RLENGTH tracked by JRT and mirror to VariableManager.voidSet RS via the VariableManager and apply it to the current reader if any.voidSet RSTART tracked by JRT (1-based) and mirror to VariableManager.voidSet SUBSEP via the VariableManager.voidsetWarningStream(PrintStream warningStream) Sets the stream that receives runtime warning messages.intSplits the string into parts separated by one or more spaces; blank first and last fields are eliminated.intSplits the string into parts separated the regular expression fs.splitTokenizer(String input, Object separator) Builds the tokenizer splittinginputby the given separator, following AWK field-splitting rules (" "splits on whitespace runs,""splits into characters, a single character is literal) and honoringIGNORECASEfor regexp separators.static StringsprintfNoCatch(Locale locale, String fmtArg, Object... arr) sprintfFunctionNoCatch.static Stringsubstr.static Stringsubstr.static inttimeSeed()timeSeed.Convert Strings, Integers, and Doubles to Strings based on the CONVFMT variable contents and the stored Locale.final booleanConverts an Integer, Double, String, Pattern, or ConditionPair to a boolean.static doubleConvert a String, Integer, or Double to Double.toInputScalar(Object value) Creates an input-derived AWK scalar value.static ObjecttoJavaScalar(Object value) Converts an internal runtime scalar to the value exposed through Java APIs.static longConvert a String, Long, or Double to Long.static ObjectuntypedToBlank(Object value) Replaces the untyped marker by AWK's assigned blank scalar.
-
Constructor Details
-
JRT
Create a JRT with explicit default output and error streams.- Parameters:
vm- The VariableManager to use with this JRT.locale- The Locale to use for number formatting.awkSink- default output sink used by plain AWK print operationserror- default error stream used for process stderr
-
-
Method Details
-
setAwkSink
Sets the sink used by defaultprintandprintfoperations.- Parameters:
sink- output sink to use
-
setErrorStream
Sets the stream used for the stderr output of spawned processes (e.g.system("...")).- Parameters:
errorStream- stream to receive process stderr
-
setWarningStream
Sets the stream that receives runtime warning messages. Warnings default toSystem.err, mirroring where gawk sends its diagnostics, and are deliberately kept apart from the process-stderr stream so they can never leak into a captured script output.- Parameters:
warningStream- stream to receive runtime warnings
-
printWarning
Prints a runtime warning message to the warning stream (stderr by default), mirroring where gawk sends its diagnostics.- Parameters:
message- warning text to print
-
getAwkSink
Returns the default output sink used byprintandprintf.- Returns:
- the current AWK sink
-
getLocale
Returns the locale used for number formatting in this runtime.- Returns:
- the runtime locale
-
isJrtManagedSpecialVariable
Returns whether the supplied variable name is managed directly by JRT rather than through the AVM runtime stack.- Parameters:
name- variable name to inspect- Returns:
truewhen the variable is a JRT-managed special variable
-
isGawkOnlySpecialVariable
Returns whether the name is a gawk-only special variable that POSIX mode treats as an ordinary identifier, likegawk --posixdoes. Shared by the parser and the interpreter so both stay in sync.- Parameters:
name- variable name to inspect- Returns:
truewhen POSIX mode must treat the name as ordinary
-
copySpecialVariables
Copies only the JRT-managed special variables from the supplied map.- Parameters:
variableMap- source variable map- Returns:
- a new map containing only JRT-managed special variables
-
prepareForExecution
Resets per-execution JRT state and re-applies the default runtime special variables for a new script or expression execution.The
defaultFsanddefaultRsparameters allow the caller to configure the initial field and record separators. Other special variables (OFS,ORS,CONVFMT,OFMT,SUBSEP) use their POSIX-mandated defaults (seeAwkconstants) which are platform-independent and therefore not parameterized. Platform-specific end-of-line handling is the responsibility of theAwkSink.- Parameters:
defaultFs- default field separator, ornullforAwk.DEFAULT_FSdefaultRs- default record separator
-
assignInitialVariables
Assign all -v variables.- Parameters:
initialVarMap- A map containing all initial variable names and their values.
-
applySpecialVariable
Applies the assignment of a single JRT-managed special variable.- Parameters:
name- variable namevalue- value to assign- Returns:
truewhen the name was a JRT-managed special variable,falsewhen the assignment was not handled
-
applySpecialVariables
Applies only the JRT-managed special variable assignments from the supplied map (FS, RS, OFS, ORS, CONVFMT, OFMT, SUBSEP, FILENAME, NF, NR, FNR, ARGC, IGNORECASE). Non-special variables are silently skipped because they require the runtime stack to be fully initialized (which happens during tuple execution).- Parameters:
variableMap- a map of variable names to values
-
assignEnvironmentVariables
Called by AVM/compiled modules to assign local environment variables to an associative array (in this case, to ENVIRON).- Parameters:
aa- The associative array to populate with environment variables. The module asserts that the associative array is empty prior to population.
-
createAwkMap
Creates an AWK-managed associative array and exposes it as a plainMapfor callers that do not need the concrete runtime type.- Parameters:
sortedArrayKeys-trueto keep keys sorted- Returns:
- a new AWK associative array
-
containsAwkKey
Checks key existence using AWK semantics when the supplied map is backed by anAssocArray, otherwise falling back to regularMapsemantics.- Parameters:
map- map to inspectkey- key to look up- Returns:
truewhen the key exists
-
getAssocArrayValue
Reads a map element using AWK semantics when the supplied map is backed by anAssocArray. For plainMapinstances, missing ornull-valued entries are exposed as the AWK blank value so later expression evaluation never receives a rawnull.- Parameters:
map- map to inspectkey- key to look up- Returns:
- the stored value, or the AWK blank value when no concrete value is present
-
getAwkStringEntry
Returns the AWK string value of an associative array entry, ornullwhen the array has no such key. This is the common way to read optional settings out of AWK arrays, such asPROCINFO["sorted_in"]orENVIRON["TZ"].- Parameters:
map- associative array to readkey- entry key- Returns:
- the entry value converted with
CONVFMT, ornullwhen the key is absent
-
toAwkString
Convert Strings, Integers, and Doubles to Strings based on the CONVFMT variable contents and the stored Locale.- Parameters:
o- Object to convert.- Returns:
- A String representation of o.
-
toDouble
Convert a String, Integer, or Double to Double.- Parameters:
o- Object to convert.- Returns:
- the "double" value of o, or 0 if invalid
-
isActuallyLong
public static boolean isActuallyLong(double d) Determines whether a double value actually represents a long integer within the limits of floating point precision.- Parameters:
d- the double value to examine- Returns:
trueifdis effectively an integer
-
toLong
Convert a String, Long, or Double to Long.- Parameters:
o- Object to convert.- Returns:
- the "long" value of o, or 0 if invalid
-
parseFieldNumber
Convert a field designator to a non-negative long, raising an AWK runtime exception when the value is invalid.- Parameters:
obj- the object identifying the field (for example, the result of a numeric expression)- Returns:
- the parsed field number as a long
-
compare2
Compares two objects. Whether to employ less-than, equals, or greater-than checks depends on the mode chosen by the callee. It handles Awk variable rules and type conversion semantics.- Parameters:
o1- The 1st object.o2- the 2nd object.mode-- < 0 - Return true if o1 < o2.
- 0 - Return true if o1 == o2.
- > 0 - Return true if o1 > o2.
- Returns:
- a boolean
-
compare2
Compares two objects likecompare2(Object, Object, int), folding case in string comparisons whenignoreCaseis set: gawk'sIGNORECASEapplies to string relational operators, not only to regexp operations.- Parameters:
o1- The 1st object.o2- the 2nd object.mode- the comparison mode, as incompare2(Object, Object, int)ignoreCase- whether string comparisons ignore case- Returns:
- a boolean
-
index
Implements theindex()builtin: the 1-based position ofneedlewithinhaystack, or 0 when absent, folding case whenIGNORECASEis set.- Parameters:
haystack- text to searchneedle- text to find- Returns:
- 1-based match position, 0 when not found
-
toJavaScalar
Converts an internal runtime scalar to the value exposed through Java APIs.- Parameters:
value- internal scalar value- Returns:
- plain Java scalar value
-
isParseableNumber
Returns whether the supplied text parses as an AWK number under this runtime's locale, as used for strnum recognition.- Parameters:
value- text to test- Returns:
truewhenvalueis an input numeric string
-
untypedToBlank
Replaces the untyped marker by AWK's assigned blank scalar. Reading a missing array element creates and returns the untyped marker (sotypeof()can see it), but an assignment must not propagate it: afterx = a[missing],xis an assigned blank scalar (typeof(x) == "unassigned"), exactly as in gawk. This is a singleinstanceofon the assignment paths.- Parameters:
value- value about to be stored by an assignment- Returns:
- the assigned blank scalar when the value was the untyped marker, otherwise the original value
-
inc
Return an object which is numerically equivalent to one plus a given object. For Integers and Doubles, this is similar to o+1. For Strings, attempts are made to convert it to a double first. If the String does not contain a numeric prefix, 1 is returned.- Parameters:
o- The object to increase.- Returns:
o + 1if o is numeric or contains a numeric prefix; otherwise,1.0
-
dec
Return an object which is numerically equivalent to one minus a given object. For Integers and Doubles, this is similar to o-1. For Strings, attempts are made to convert it to a double first. If the String does not contain a numeric prefix, -1 is returned.- Parameters:
o- The object to increase.- Returns:
o - 1if o is numeric or contains a numeric prefix; otherwise,-1.0
-
toBoolean
Converts an Integer, Double, String, Pattern, or ConditionPair to a boolean.- Parameters:
o- The object to convert to a boolean.- Returns:
- For the following class types for o:
- Integer - o.intValue() != 0
- Long - o.longValue() != 0
- Double - o.doubleValue() != 0
- String - o.length() > 0
- UninitializedObject - false
- Pattern - $0 ~ o
-
split
Splits the string into parts separated by one or more spaces; blank first and last fields are eliminated. This conforms to the 2-argument version of AWK's split function.- Parameters:
array- The array to populate.string- The string to split.- Returns:
- The number of parts resulting from this split operation.
-
split
Splits the string into parts separated the regular expression fs. This conforms to the 3-argument version of AWK's split function.If fs is blank, it behaves similar to the 2-arg version of AWK's split function.
- Parameters:
fieldSeparator- Field separator regular expression.array- The array to populate.string- The string to split.- Returns:
- The number of parts resulting from this split operation.
-
getPartitioningReader
Returns the underlyingPartitioningReadercurrently in use by the activeInputSource, ornullif the source is not stream-based.- Returns:
- the active reader, or
null
-
getInputLine
Getter for the field
inputLine.- Returns:
- the current input line scalar value, or
null
-
getNF
Retrieve the current value of NF. When fields are initialized this returns the number of fields in $0; otherwise 0.- Returns:
- current NF value
-
setNF
Set NF to the specified value and update $0 and fields accordingly.- Parameters:
nfObject- value to assign to NF
-
getNR
Get the current NR value as tracked by JRT.- Returns:
- current NR
-
setNR
Assign NR to a specific value; also updates the VariableManager copy.- Parameters:
value- value to assign
-
getFNR
Get the current FNR value as tracked by JRT.- Returns:
- current FNR
-
setFNR
Assign FNR to a specific value; also updates the VariableManager copy.- Parameters:
value- value to assign
-
getFSVar
Get FS from the VariableManager.- Returns:
- FS value
-
getFSString
Returns the current FS value as a string.- Returns:
- current field separator
-
setFS
Set FS via the VariableManager.- Parameters:
value- new FS value
-
setIGNORECASE
Sets IGNORECASE, precomputing its truth value so regexp operations can test a boolean instead of coercing the raw value on every match.- Parameters:
value- new IGNORECASE value
-
getIGNORECASEVar
Get IGNORECASE from the VariableManager.- Returns:
- IGNORECASE value
-
isIgnoreCase
public boolean isIgnoreCase()Returns whether IGNORECASE is currently nonzero, making regexp operations case-insensitive. The truth value is precomputed when IGNORECASE is assigned.- Returns:
truewhen IGNORECASE is nonzero
-
regexpFlags
public int regexpFlags()Returns thePatternflags implied by the currentIGNORECASEsetting; dynamic regexps should be compiled with these flags.- Returns:
Pattern.CASE_INSENSITIVEwhenIGNORECASEis truthy, 0 otherwise
-
replaceFirst
sub()functionality: replaces the first match ofereinorigwithrepl, honoringIGNORECASE. The substituted text is available throughgetReplaceResult().- Parameters:
orig- original textrepl- AWK replacement textere- regular expression- Returns:
- number of replacements performed (0 or 1)
-
replaceAll
gsub()functionality: replaces every match ofereinorigwithrepl, honoringIGNORECASE. The substituted text is available throughgetReplaceResult().- Parameters:
orig- original textrepl- AWK replacement textere- regular expression- Returns:
- number of replacements performed
-
getReplaceResult
Returns the text produced by the lastreplaceFirst(java.lang.String, java.lang.String, java.lang.String)orreplaceAll(java.lang.String, java.lang.String, java.lang.String)call.- Returns:
- substituted text
-
matches
Evaluates the AWK match operator (text ~ regexp), honoringIGNORECASEfor both precompiled regexp constants and dynamic expressions.- Parameters:
text- text to matchregexp- precompiledPatternor dynamic regexp text- Returns:
truewhen the regexp matches anywhere in the text
-
matchPosition
match()functionality: locatesereinshonoringIGNORECASE, updatingRSTARTandRLENGTH.- Parameters:
s- text to searchere- regular expression- Returns:
- the match position (
RSTART), or 0 when there is no match
-
splitTokenizer
Builds the tokenizer splittinginputby the given separator, following AWK field-splitting rules (" "splits on whitespace runs,""splits into characters, a single character is literal) and honoringIGNORECASEfor regexp separators. A precompiledPatternseparator (a regexp literal) is used directly.- Parameters:
input- text to splitseparator- field separator: precompiled pattern or text- Returns:
- tokenizer producing the split parts
-
prepareReplacement
Converts an AWK replacement text into a JavaMatcherreplacement:&becomes the whole match,\&a literal ampersand, and$is escaped.- Parameters:
awkRepl- AWK replacement textbackreferences- whether\Ndenotes capture groupN, as in gawk'sgensub(); whenfalse,\Nstays literal as insub()andgsub()- Returns:
- the equivalent Java replacement string
-
prepareReplacement
Converts an AWK replacement text into a JavaMatcherreplacement, resolving gensub-style backreferences against a known number of capture groups:\NbeyondmaxGroupis replaced by the empty string, as gawk does, instead of producing a group reference that would make the matcher throw.- Parameters:
awkRepl- AWK replacement textmaxGroup- highest valid capture group number, or a negative value to disable backreferences entirely (sub()/gsub()semantics)- Returns:
- the equivalent Java replacement string
-
caseAwarePattern
Returns the pattern itself, or its case-insensitive twin whenIGNORECASEis set. Twins are compiled once and cached here: the JDK'sPattern.compile(String)performs no caching of its own (every call reparses the expression), so dropping this cache would recompile the regexp on every record matched against a regexp constant.- Parameters:
pattern- base pattern- Returns:
- pattern honoring the current
IGNORECASEsetting
-
dynamicPattern
Compiles a dynamic (string) regexp with the flags implied by the currentIGNORECASEsetting, caching compiled patterns by expression text: dynamic regexps are typically reused across records (for example agsub(dynstr, ...)loop), and the JDK'sPattern.compile(String, int)reparses the expression on every call. EachIGNORECASEsetting has its own cache; the settings cannot share one becausePattern.flags()reflects inline flag constructs such as(?i), so it cannot tell apart a pattern compiled under the other setting.- Parameters:
ere- dynamic regular expression text- Returns:
- the compiled pattern honoring the current
IGNORECASEsetting
-
getRSVar
Get RS from the VariableManager.- Returns:
- RS value
-
getRSString
Returns the current RS value as a string.- Returns:
- current record separator
-
setRS
Set RS via the VariableManager and apply it to the current reader if any.- Parameters:
value- new RS value
-
getOFSVar
Get OFS from the VariableManager.- Returns:
- OFS value
-
getOFSString
Returns the current OFS value as a string.- Returns:
- current output field separator
-
setOFS
Set OFS via the VariableManager.- Parameters:
value- new OFS value
-
getORSVar
Get ORS from the VariableManager.- Returns:
- ORS value
-
getORSString
Returns the current ORS value as a string.- Returns:
- current output record separator
-
setORS
Set ORS via the VariableManager.- Parameters:
value- new ORS value
-
getRSTART
Get RSTART tracked by JRT (1-based).- Returns:
- current RSTART
-
setRSTART
Set RSTART tracked by JRT (1-based) and mirror to VariableManager.- Parameters:
value- new RSTART
-
getRLENGTH
Get RLENGTH tracked by JRT.- Returns:
- current RLENGTH
-
setRLENGTH
Set RLENGTH tracked by JRT and mirror to VariableManager.- Parameters:
value- new RLENGTH
-
getFILENAME
Get FILENAME as tracked by JRT.- Returns:
- current FILENAME (empty string for stdin/pipe)
-
setFILENAMEViaJrt
Set FILENAME through VariableManager and update JRT mirror.- Parameters:
name- file name to set
-
getERRNO
Get ERRNO as tracked by JRT.- Returns:
- current ERRNO (empty string when no input error is pending)
-
setERRNO
Set ERRNO tracked by JRT.- Parameters:
value- new ERRNO value
-
getARGIND
Get ARGIND as tracked by JRT.- Returns:
- ARGV index of the current input file (0 before any file is open)
-
setARGIND
Set ARGIND tracked by JRT.- Parameters:
value- new ARGIND value
-
getSUBSEPVar
Get SUBSEP from the VariableManager.- Returns:
- SUBSEP value
-
getSUBSEPString
Returns the current SUBSEP value as a string.- Returns:
- current multidimensional-array subscript separator
-
setSUBSEP
Set SUBSEP via the VariableManager.- Parameters:
value- new SUBSEP value
-
getCONVFMTVar
Get CONVFMT from the VariableManager.- Returns:
- CONVFMT value
-
getCONVFMTString
Returns the current CONVFMT value as a string.- Returns:
- current numeric conversion format
-
setCONVFMT
Set CONVFMT via the VariableManager.- Parameters:
value- new CONVFMT value
-
getOFMTString
Get OFMT from the VariableManager.- Returns:
- OFMT value
-
setOFMT
Set OFMT via the VariableManager.- Parameters:
value- new OFMT value
-
getARGCVar
Get ARGC from the VariableManager.- Returns:
- ARGC value
-
setARGC
Set ARGC via the VariableManager.- Parameters:
value- new ARGC value
-
setInputLine
Setter for the field
inputLine.- Parameters:
inputLineParam- input value
-
toInputScalar
Creates an input-derived AWK scalar value.- Parameters:
value- input text- Returns:
- input-derived scalar value
-
consumeInput
Attempt to consume one record from a structured input source and expose it as the current input record.- Parameters:
source- source strategy that provides records and optional pre-split fields- Returns:
trueif a record was consumed;falsewhen the source is exhausted- Throws:
IOException- if the source raises an I/O error
-
consumeCurrentFileInput
Attempt to consume one record from the current input file only, without ever advancing to the next input file. Used by the per-file main input loop when BEGINFILE/ENDFILE rules ornextfileare present, so that the ENDFILE rules can run at each file boundary.When the current input file could not be opened (a pending ERRNO set by
advanceToNextFile(InputSource)that nonextfileconsumed), the usual fatal error is raised, mirroring gawk.- Parameters:
source- source strategy that provides records and optional pre-split fields- Returns:
trueif a record was consumed;falseat the end of the current input file- Throws:
IOException- if the source raises an I/O error
-
consumeCurrentFileInputToTarget
Attempt to consume one record of the current input file only forgetline target, returning the input value and leaving the current input record state untouched. Used instead ofconsumeInputToTarget(InputSource)while the per-file main input loop is active, so agetlinein an action never crosses a file boundary behind the BEGINFILE/ENDFILE rules' back.- Parameters:
source- source strategy that provides records and optional pre-split fields- Returns:
- the consumed input value, or
nullat the end of the current input file - Throws:
IOException- if the source raises an I/O error
-
advanceToNextFile
Advance the main input to the next input file, applying pendingname=valuecommand-line assignments along the way. On success, FILENAME, FNR, ARGIND, and ERRNO are updated and$0is cleared, so the BEGINFILE rules observe the new file. A file that cannot be opened is still reported as available, with ERRNO carrying the error description (gawk BEGINFILE error handling).- Parameters:
source- source strategy that provides records and optional pre-split fields- Returns:
truewhen a new input file (or the initial stdin stream) is available;falsewhen input is exhausted- Throws:
IOException- if an I/O error occurs while traversing ARGV
-
hasPendingInputFileError
Returns whether the current input file of the given source failed to open, leaving a pending error that only anextfilestatement in a BEGINFILE rule may bypass.- Parameters:
source- source strategy that provides records- Returns:
truewhen the current input file could not be opened
-
consumeInputToTarget
Attempt to consume one record from a structured input source forgetline target, returning the input value and leaving the current input record state untouched.- Parameters:
source- source strategy that provides records and optional pre-split fields- Returns:
- the consumed input value, or
nullwhen the source is exhausted - Throws:
IOException- if the source raises an I/O error
-
consumeInputForEval
Consume at most one record from a structured source for expression evaluation.- Parameters:
source- source strategy that provides records and optional pre-split fields- Returns:
trueif a record was consumed,falseotherwise- Throws:
IOException- if the source raises an I/O error
-
initializeInputFields
Initialize$0..$NFfrom a pre-split field list.- Parameters:
record- current$0textpreFields- current fields where index0is$1
-
jrtParseFields
public void jrtParseFields()Splits $0 into $1, $2, etc. Called when an update to $0 has occurred. -
hasInputFields
public boolean hasInputFields()- Returns:
- true if at least one input field has been initialized.
-
jrtSetNF
Adjust the current input field list and $0 when NF is updated by the AWK script. Fields are either truncated or extended with empty values so thatNFtruly reflects the number of fields.- Parameters:
nfObj- New value for NF
-
jrtGetInputField
Retrieve the contents of a particular input field.- Parameters:
fieldnumObj- Object referring to the field number.- Returns:
- Contents of the field.
-
jrtGetInputField
jrtGetInputField.
- Parameters:
fieldnum- a long- Returns:
- a
Objectobject
-
jrtSetInputField
Stores value_obj into an input field.- Parameters:
valueObj- The RHS of the assignment.fieldNum- field number to update.- Returns:
- A string representation of valueObj.
-
rebuildDollarZeroFromFields
protected void rebuildDollarZeroFromFields() -
jrtConsumeFileInputForGetline
jrtConsumeFileInputForGetline.
-
jrtConsumeCommandInputForGetline
Retrieve the next line of output from a command, executing the command if necessary and store it to $0.- Parameters:
cmdString- The command to execute.- Returns:
- Integer(1) if successful, Integer(0) if no more input is available, Integer(-1) upon an IO error.
-
jrtGetInputString
Retrieve $0.- Returns:
- The contents of the $0 input field.
-
getOutputFiles
Getter for the field
outputFiles.- Returns:
- a
Mapobject
-
getFileAwkSink
Resolves the sink used by file redirection.- Parameters:
fileNameParam- target file nameappend- whether output should be appended- Returns:
- the sink that writes to the requested file
-
getPipeAwkSink
Resolves the sink used by pipe redirection.- Parameters:
cmd- command to execute- Returns:
- the sink connected to the process stdin
-
printDefault
Writes a standard AWKprintoperation to the default output.- Parameters:
values- values to print- Throws:
IOException- if the sink cannot be written to
-
printToFile
Writes a standard AWKprintoperation to a redirected file.- Parameters:
fileNameParam- target file nameappend- whether output should be appendedvalues- values to print; an empty array prints$0- Throws:
IOException- if the sink cannot be written to
-
printToProcess
Writes a standard AWKprintoperation to a redirected process.- Parameters:
cmd- command to executevalues- values to print; an empty array prints$0- Throws:
IOException- if the sink cannot be written to
-
printfDefault
Writes a formatted AWK output string to the specified sink.- Parameters:
format- format string passed toprintfvalues- values supplied after the format string- Throws:
IOException- if the sink cannot be written to
-
printfToFile
public void printfToFile(String fileNameParam, boolean append, String format, Object[] values) throws IOException Writes formatted AWK output to a redirected file.- Parameters:
fileNameParam- target file nameappend- whether output should be appendedformat- format string passed toprintfvalues- values supplied after the format string- Throws:
IOException- if the sink cannot be written to
-
printfToProcess
Writes formatted AWK output to a redirected process.- Parameters:
cmd- command to executeformat- format string passed toprintfvalues- values supplied after the format string- Throws:
IOException- if the sink cannot be written to
-
jrtGetPrintStream
Retrieve the PrintStream which writes to a particular file, creating the PrintStream if necessary.- Parameters:
fileNameParam- The file which to write the contents of the PrintStream.append- true to append to the file, false to overwrite the file.- Returns:
- a
PrintStreamobject
-
jrtConsumeFileInput
jrtConsumeFileInput.
- Parameters:
fileNameParam- aStringobject- Returns:
- a boolean
- Throws:
IOException- if any.
-
jrtConsumeCommandInput
jrtConsumeCommandInput.
- Parameters:
cmd- aStringobject- Returns:
- a boolean
- Throws:
IOException- if any.
-
jrtSpawnForOutput
Retrieve the PrintStream which shuttles data to stdin for a process, executing the process if necessary. Threads are created to shuttle the data to/from the process.- Parameters:
cmd- The command to execute.- Returns:
- The PrintStream which to write to provide input data to the process.
-
jrtClose
Attempt to close an open stream, whether it is an input file, output file, input process, or output process.The specification did not describe AWK behavior when attempting to close streams/processes with the same file/command name. In this case, all open streams with this name are closed.
- Parameters:
fileNameParam- The filename/command process to close.- Returns:
- Integer(0) upon a successful close, Integer(-1) otherwise.
-
jrtCloseAll
public void jrtCloseAll()jrtCloseAll.
-
jrtSystem
Executes the command specified by cmd and waits for termination, returning an Integer object containing the return code. stdin to this process is closed while threads are created to shuttle stdout and stderr of the command to stdout/stderr of the calling process.- Parameters:
cmd- The command to execute.- Returns:
- Integer(return_code) of the created process. Integer(-1) is returned on an IO error.
-
sprintfNoCatch
public static String sprintfNoCatch(Locale locale, String fmtArg, Object... arr) throws IllegalFormatException sprintfFunctionNoCatch.
- Parameters:
locale- aLocaleobjectfmtArg- aStringobjectarr- an array ofObjectobjects- Returns:
- a
Stringobject - Throws:
IllegalFormatException- if any.
-
printfNoCatch
printfFunctionNoCatch.
-
printfNoCatch
printfFunctionNoCatch.
- Parameters:
ps- aPrintStreamobjectlocale- aLocaleobjectfmtArg- aStringobjectarr- an array ofObjectobjects
-
substr
substr.
-
substr
substr.
-
timeSeed
public static int timeSeed()timeSeed.
- Returns:
- a int
-
newRandom
newRandom.
- Parameters:
seed- a int- Returns:
- a
Randomobject
-
applyRS
applyRS.
- Parameters:
rsObj- aObjectobject
-