1

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

3
  • 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) Commented Apr 15, 2021 at 6:38
  • @StéphaneChazelas the last character was a line terminator \n and the . was the second last character Commented Apr 15, 2021 at 6: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? Commented Apr 15, 2021 at 7:23

1 Answer 1

1

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.

1
  • More likely a space after the dot. Commented Apr 15, 2021 at 10:32

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.