Question

How would i read lines with format intA intB intC intD charP where "charA" is optional? Also there is possibility of a comment marked with # text

I tried something like this

FILE = 'test.txt'
while IFS=' ' read -r numA numB numC numD charP
  #do something with this
done < FILE

but i don't know whether i'm on a right path and what to do with charP

sample:

# comment
12345678 24 15 3 p
87654321 11 4 8
43218765 27 10 2 P
Was it helpful?

Solution

You're on the right track, but there are problems with your code:

  • Remove the spaces around = in the FILE = line - your script will break otherwise.
  • Your while statement is missing a do line (or ; do appended to the while line directly).
  • Instead of referring to variable $FILE in the done line, your passing the string literal FILE instead - use "$FILE" (the quotes are there to ensure that it works even with filenames that have embedded spaces and other chars. interpreted by the shell).

As for ignoring the optional character on the end of the line: simply adding another variable, as your code already does (charP), is sufficient - it will then be assigned the remainder of the line, and you can just ignore it.

If we put it together, adding the code for ignoring comment lines, we get:

FILE='test.txt'
while IFS=' ' read -r numA numB numC numD charP
do
  if [[ $numA != \#* ]]; then # ignore comment lines
      # ... do something
  fi
done < "$FILE"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top