read lines from a txt file in bash

折月煮酒 提交于 2019-12-11 13:06:34

问题


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"


来源:https://stackoverflow.com/questions/22897354/read-lines-from-a-txt-file-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!