本文介绍了从bash中的txt文件读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何读取格式为intA intB intC intD charP的行,其中"charA"是可选的?还有可能用# text

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

我尝试过类似的事情

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

但是我不知道我走的路是否正确以及如何处理charP

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

样本:

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

推荐答案

您处在正确的轨道上,但是您的代码存在问题:

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

  • 删除FILE =行中=周围的空格-否则脚本将中断.
  • 您的while语句缺少do行(或直接附加到while行的; do).
  • 您将传递 string文字 FILE而不是在done行中引用变量 $FILE,而是使用"$FILE"(引号是在那里确保即使在文件名中包含嵌入空格和其他字符(由Shell解释)时也可以使用.
  • 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).

至于忽略行尾的可选字符:只需添加另一个变量即可,因为您的代码已经这样做了(charP),就足够了-然后将为其分配 remainder 行,您可以忽略它.

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中的txt文件读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:06