如何使用Bash遍历文本文件的每一行?

使用此脚本:

echo "Start!"
for p in (peptides.txt)
do
    echo "${p}"
done

我在屏幕上看到这个输出:

Start!
./runPep.sh: line 3: syntax error near unexpected token `('
./runPep.sh: line 3: `for p in (peptides.txt)'

(后来我想用$p做一些比输出到屏幕更复杂的事情。)


环境变量SHELL是(来自env):

SHELL=/bin/bash

/bin/bash—版本输出:

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文件包含:

RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL

当前回答

@彼得:这可能对你有用-

echo "Start!";for p in $(cat ./pep); do
echo $p
done

这将返回输出-

Start!
RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL

其他回答

#!/bin/bash
#
# Change the file name from "test" to desired input file 
# (The comments in bash are prefixed with #'s)
for x in $(cat test.txt)
do
    echo $x
done

选项1a:While循环:一次单行:输入重定向

#!/bin/bash
filename='peptides.txt'
echo Start
while read p; do 
    echo "$p"
done < "$filename"

选项1b:While循环:一次单行:打开文件,从文件描述符中读取(在本例中为文件描述符#4)。

#!/bin/bash
filename='peptides.txt'
exec 4<"$filename"
echo Start
while read -u4 p ; do
    echo "$p"
done

使用while循环,如下所示:

while IFS= read -r line; do
   echo "$line"
done <file

笔记:

如果不正确设置IFS,将丢失缩进。您几乎应该始终在read中使用-r选项。不读取带有for的行

我喜欢使用xargs而不是while。xargs功能强大,命令行友好

cat peptides.txt | xargs-I%sh-c“echo%”

使用xargs,还可以使用-t添加详细信息,使用-p添加验证

对于`cat peptides.txt中的p`做echo“${p}”完成