问题描述
我将如何读取格式为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 theFILE =
line - your script will break otherwise. - Your
while
statement is missing ado
line (or; do
appended to thewhile
line directly). - Instead of referring to variable
$FILE
in thedone
line, your passing the string literalFILE
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文件读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!