0

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.

  • Since this is bash: printf '%s\n' "${l:2:1}". Per the man page, the built-in echo 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
  • https://unix.stackexchange.com/q/169716/170373 – ilkkachu Mar 21 '23 at 05:53
  • "Per Hacker Rank, the expected output is null/blank." -- so the task is not just to print the third character, then. (You could have linked to the task so we could also see it) "Unfortunately it does not show what my actual output was" -- you could run the script on your own system to see – ilkkachu Mar 21 '23 at 05:55

0 Answers0