I'm doing some Linux Shell exercises in Hacker Rank.
One of the problems is to take a text file containing N lines of ASCII characters and print out only the 3rd charater in each line.
I came up with:
while read l; do
printf "${l:2:1}\n"
# or echo ${l:2:1}
done
This works fine for every test case except when the 3rd character happens to be "-" (hyphen). Per Hacker Rank, the expected output is null/blank. Unfortunately it does not show what my actual output was - I assume it was "-" which is not equal to their proposed null/blank.
The line in the failed test case is:
M – Municipality
Please advise.
bash
:printf '%s\n' "${l:2:1}"
. Per the man page, the built-inecho
doesn't interpret--
to mean the end of options, so it's likely to still swallow a lone-
as the first argument. However, if I padded the argument at the front with a space, it worked for me:echo " ${l:2:1}"
. I'm not sure that will work in all versions of bash on all Linux/Unix/MacOS/etc., though. – Sotto Voce Mar 21 '23 at 00:00