Skip to content

Commit

Permalink
Set NR and FILENAME variables
Browse files Browse the repository at this point in the history
  • Loading branch information
mohd-akram committed Jan 6, 2024
1 parent 6622f59 commit e78c029
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 6 deletions.
5 changes: 3 additions & 2 deletions jawk
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ if [ ! "$f" ]; then file=-; fi

jawk='
BEGIN { JSON="\1"; TYPE="\2"; __KEYS="\3"; FS="\n"; __jawk__init() }
{ __parse_value($0); $0 = _[JSON] }
{ __parse_value($0); $0 = _[JSON]; NR = ++__nr; FILENAME = __filename }
function __jawk__init(i) {
__CHAR[0] = "\0"; __CHAR[1] = "\1"; __CHAR[2] = "\2"
Expand Down Expand Up @@ -310,4 +310,5 @@ SPACE='[[:space:]]+'
: ${AWK=$(command -v gawk || echo awk)}
: ${EGREP=$(command -v ugrep || echo 'grep -E')}

$EGREP -o "$STRING|$NUMBER|$KEYWORD|[][{}:,]" "$file" | $AWK "$@" "$jawk$prog"
$EGREP -o "$STRING|$NUMBER|$KEYWORD|[][{}:,]" "$file" |
$AWK -v __filename="$file" "$@" "$jawk$prog"
2 changes: 1 addition & 1 deletion src/jawk.awk
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
BEGIN { JSON="\1"; TYPE="\2"; __KEYS="\3"; FS="\n"; __jawk__init() }
{ __parse_value($0); $0 = _[JSON] }
{ __parse_value($0); $0 = _[JSON]; NR = ++__nr; FILENAME = __filename }

function __jawk__init(i) {
__CHAR[0] = "\0"; __CHAR[1] = "\1"; __CHAR[2] = "\2"
Expand Down
3 changes: 2 additions & 1 deletion src/jawk.sh
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,5 @@ SPACE='[[:space:]]+'
: ${AWK=$(command -v gawk || echo awk)}
: ${EGREP=$(command -v ugrep || echo 'grep -E')}

$EGREP -o "$STRING|$NUMBER|$KEYWORD|[][{}:,]" "$file" | $AWK "$@" "$jawk$prog"
$EGREP -o "$STRING|$NUMBER|$KEYWORD|[][{}:,]" "$file" |
$AWK -v __filename="$file" "$@" "$jawk$prog"
8 changes: 6 additions & 2 deletions test/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -169,5 +169,9 @@ out=$(printf '{"a":1, \n"b":2}' | jawk '{print _["b"]}')

test "file"
echo '{"age":10}' >test/test.json
out=$(jawk '{print _["age"]}' test/test.json; rm test/test.json)
[ "$out" = "10" ]
out=$(jawk '{print FILENAME;print _["age"]}' test/test.json; rm test/test.json)
[ "$out" = "$(printf 'test/test.json\n10')" ]

test "NR"
out=$(printf '{\n"age":10\n}\n{\n"age":12\n}' | jawk '{print NR}')
[ "$out" = "$(printf '1\n2')" ]

0 comments on commit e78c029

Please sign in to comment.