read lines from a txt file in bash

2019-08-04 20:03发布

问题:

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

回答1:

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"


标签: bash shell line