问题描述
如何使用 Bash 遍历文本文件的每一行?
How do I iterate through each line of a text file with Bash?
使用这个脚本:
echo "Start!"
for p in (peptides.txt)
do
echo "${p}"
done
我在屏幕上看到这个输出:
I get this output on the screen:
Start!
./runPep.sh: line 3: syntax error near unexpected token `('
./runPep.sh: line 3: `for p in (peptides.txt)'
(后来我想用 $p
做一些更复杂的事情,而不仅仅是输出到屏幕.)
(Later I want to do something more complicated with $p
than just output to the screen.)
环境变量SHELL是(来自env):
The environment variable SHELL is (from env):
SHELL=/bin/bash
/bin/bash --version
输出:
GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
cat/proc/version
输出:
Linux version 2.6.18.2-34-default (geeko@buildhost) (gcc version 4.1.2 20061115 (prerelease) (SUSE Linux)) #1 SMP Mon Nov 27 11:46:27 UTC 2006
peptides.txt 文件包含:
The file peptides.txt contains:
RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL
推荐答案
一种方法是:
while read p; do
echo "$p"
done <peptides.txt
正如评论中所指出的,这具有修剪前导空格、解释反斜杠序列以及在缺少终止换行符的情况下跳过最后一行的副作用.如果存在这些问题,您可以这样做:
As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do:
while IFS="" read -r p || [ -n "$p" ]
do
printf '%s
' "$p"
done < peptides.txt
例外,如果 循环体可能从标准输入读取,您可以使用不同的文件描述符打开文件:
Exceptionally, if the loop body may read from standard input, you can open the file using a different file descriptor:
while read -u 10 p; do
...
done 10<peptides.txt
这里,10 只是一个任意数字(不同于 0、1、2).
Here, 10 is just an arbitrary number (different from 0, 1, 2).
这篇关于在 Bash 中循环遍历文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!