From e78c029de75e62980a25d960cadc175a9786cb92 Mon Sep 17 00:00:00 2001
From: Mohamed Akram <mohd.akram@outlook.com>
Date: Sat, 6 Jan 2024 22:11:51 +0400
Subject: [PATCH] Set NR and FILENAME variables

---
 jawk         | 5 +++--
 src/jawk.awk | 2 +-
 src/jawk.sh  | 3 ++-
 test/run.sh  | 8 ++++++--
 4 files changed, 12 insertions(+), 6 deletions(-)

diff --git a/jawk b/jawk
index eb8b6b5..fef4486 100755
--- a/jawk
+++ b/jawk
@@ -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"
@@ -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"
diff --git a/src/jawk.awk b/src/jawk.awk
index 5154955..e6c8095 100644
--- a/src/jawk.awk
+++ b/src/jawk.awk
@@ -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"
diff --git a/src/jawk.sh b/src/jawk.sh
index 6908938..7b1411c 100755
--- a/src/jawk.sh
+++ b/src/jawk.sh
@@ -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"
diff --git a/test/run.sh b/test/run.sh
index d2671f8..e663fd2 100755
--- a/test/run.sh
+++ b/test/run.sh
@@ -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')" ]