Skip to content

Instantly share code, notes, and snippets.

@JesseEisen
Created November 7, 2015 09:05
Show Gist options
  • Save JesseEisen/4fef2bf5524cc3c85e7e to your computer and use it in GitHub Desktop.
Save JesseEisen/4fef2bf5524cc3c85e7e to your computer and use it in GitHub Desktop.
Use awk to parse a expression
#!/bin/awk
# input: a:=10
# output: the value is 10
BEGIN{ PrintRes() }
function parse() {
if(tok == "(eof)") return "(eof)"
while(length(line) == 0)
if(getline line == 0)
return tok = "(eof)"
sub(/^[ \t]+/,"",line)
if(match(line,/^[A-Za-z_][A-Za-z_0-9]*/) || match(line,/^(=|:=)/) ||
match(line,/^-?([0-9]+\.?[0-9]*|\.[0-9]+)/) || match(line,/^./)){
tok = substr(line,1,RLENGTH)
line = substr(line,RLENGTH+1)
return tok
}
}
function PrintRes(){
parse()
while(tok != "(eof)"){
if(temp == ":=")
value = tok
temp = tok
parse()
}
print "The value is", value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment