skip lines while reading a file

Hi Experts,

I am tryin to read a file and while doing so i need to skip the lines which start with a hash (#) char.

I thought of using a goto command but a lot of guys on this site say its not the good way to program. Moreover I am using a ksh shell which deos not support goto command.

Below is the algo I am using; which definately doesn't work. I need a logic to substitute GOTO command. I have thought of using case logic and also functions; but they some how dont fit well with the work I am trying to do. Let me know if you need more details/info

Please advise guys.

Thanks in advance. :b:

 
cat <file name> | while read i
do 
      if [[ <hash char enountered> ]]; then
       goto end_of_pgm
      fi
etc 
etc
etc
end_of_pgm
   echo $i
done

Even though you are saying that you want to skip lines that start with "#", at the same time you say that you want to quit when you see it.

If you want to skip "#":

!/usr/bin/ksh
egrep -v '^#' inp_file |
while read mLine
do
  echo "mLine = <${mLine}>"
done

If you want to quit when "#" appears:

!/usr/bin/ksh
sed -n '/^#/q;p' inp_file |
while read mLine
do
  echo "mLine = <${mLine}>"
done
1 Like

Thanks for your reply.
Sorry if I was not clear. Its not that i want to quit i want to skip that particular line and then proceed to the next line.

Hope this clarifies.

---------- Post updated at 02:52 PM ---------- Previous update was at 02:20 PM ----------

Hi Shell Life,
I used the code snippet you provided and with a little bit of modifications i was able to use it. Thanks fo all the help.

Appreciate it.

while IFS= read -r line; do
    case $i in
        \#*) continue;;
    esac
    printf '%s\n' "$i"
done

Of course, you'll need to feed the while loop with a pipe or a redirect or its inherited stdin.

Regards,
Alister

---------- Post updated at 05:32 PM ---------- Previous update was at 05:26 PM ----------

Don't blindly follow any mantras. In certain situations (complex error handling, for example), a well-utilized goto can significantly simplify code, and simpler code is easier to read, maintain, less buggy and perhaps faster.

Regards,
Alister

An interesting discussion with Linus Torvalds about the pros and cons of goto statements:

Linux: Using goto In Kernel Code | KernelTrap

1 Like