Use double quotes to preserve the newlines
You must sandwich the LOG_BUF
between double quotes to preserve the newlines, so change the last line to this:
$ echo "${LOG_BUF}" | awk '/pat/{printf("%d %s", NR, $0); print ""}; END{print ""}'
1 pat TEST_a
2 pat TEST_b
4 pat TEST_d
Using shellcheck
As Ed Morton - SO stop bullying pointed out in the comments, it is advised to run a shellcheck on shell scripts before posting questions on SO. Doing so would show the following result:
$ shellcheck script.sh
In script.sh line 10:
echo ${LOG_BUF} | awk 'BEGIN{}; /pat/{printf("%d %s", NR, $0); printf("\n")}; END{printf("\n")}'
^--------^ SC2086 (info): Double quote to prevent globbing and word splitting.
Did you mean:
echo "${LOG_BUF}" | awk 'BEGIN{}; /pat/{printf("%d %s", NR, $0); printf("\n")}; END{printf("\n")}'
For more information:
https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
Using read
instead of cat
On another note, you may want to use read
instead of cat
to assign a heredoc value to a variable in bash, the following code snippet is inspired from this SO answer, I encourage you to check it out for more details:
$ read -r -d '' LOG_BUF <<-'EOF'
pat TEST_a
pat TEST_b
TEST_c
pat TEST_d
EOF
$ echo "$LOG_BUF"
pat TEST_a
pat TEST_b
TEST_c
pat TEST_d