0

I am new to bash and Linux and not sure why the last character of my selected line isn't appearing empty when it isn't empty. In my code, I am testing if the last character of my second last line == " " if so I would like to echo "yes" otherwise echo "no".

here is my code

Line=$(tail -n-2 file | head -n1)
echo "$Line"
echo "${Line: -1}"
if [ "${Line: -1}" == " " ]; then
    echo "yes";
else
    echo "no";
fi

the file consistes of:

xxxxxxxxxxxx
xx x x xxx x
xxx xx xxx x
x x xxx xx .
xxxxxxxxxxxx

the output for this is:

x x xxx xx .

yes

I am not sure why when I do echo "${Line: -1}" the output is empty but the output is as expected when I am doing echo "$Line"

any suggestions how I can fix this, thanks

  • 1
    PIpe the output to sed -n l (that's lower case L) to see if there's some invisible characters after that dot such as space, tab or carriage return (if the file comes from Microsoft land) – Stéphane Chazelas Apr 15 '21 at 06:38
  • @StéphaneChazelas the last character was a line terminator \n and the . was the second last character – ActuallyMosses Apr 15 '21 at 06:53
  • There are several of you all trying to solve the same piece of coursework. All hitting the same problem(s). Why not work together? – Chris Davies Apr 15 '21 at 07:23

1 Answers1

0

You must have a white space in the end of the file, otherwise it won't print blank character and the condition won't cause print of "yes".

cat -ve <file>

or as others wrote

sed -n l <file>

If you want to "sanitize" (ie. strip whitespaces), I would recommend to create a separate function and process your input.

Jiri B
  • 541
  • 1
  • 7
  • 16