如何使用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

其他回答

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

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

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

cat peptides.txt | while read line 
do
   # do something with $line here
done

以及单衬里变体:

cat peptides.txt | while read line; do something_with_$line_here; done

如果没有换行符,这些选项将跳过文件的最后一行。

您可以通过以下方式避免此问题:

cat peptides.txt | while read line || [[ -n $line ]];
do
   # do something with $line here
done

这来得很晚,但考虑到这可能会对某人有所帮助,我补充了答案。同样,这可能不是最好的方法。head命令可以与-n参数一起使用,从文件开头读取n行,同样,tail命令可以用于从底部读取。现在,要从文件中提取第n行,我们需要头n行,通过管道将数据传输到管道数据中仅1行的尾部。

   TOTAL_LINES=`wc -l $USER_FILE | cut -d " " -f1 `
   echo $TOTAL_LINES       # To validate total lines in the file

   for (( i=1 ; i <= $TOTAL_LINES; i++ ))
   do
      LINE=`head -n$i $USER_FILE | tail -n1`
      echo $LINE
   done

这并不比其他答案更好,但这是在没有空格的文件中完成工作的又一种方法(请参见注释)。我发现我经常需要一行程序来挖掘文本文件中的列表,而不需要使用单独的脚本文件。

for word in $(cat peptides.txt); do echo $word; done

这种格式允许我将其全部放在一个命令行中。将“echo$word”部分更改为您想要的任何内容,您可以发出多个以分号分隔的命令。下面的示例使用文件的内容作为您可能编写的其他两个脚本的参数。

for word in $(cat peptides.txt); do cmd_a.sh $word; cmd_b.py $word; done

或者,如果您打算像流编辑器一样使用它(学习sed),可以将输出转储到另一个文件,如下所示。

for word in $(cat peptides.txt); do cmd_a.sh $word; cmd_b.py $word; done > outfile.txt

我使用了上面写的这些,因为我使用的是文本文件,我在其中每行创建了一个单词。(请参见注释)如果您有空格不想拆分单词/行,那么它会变得有点难看,但相同的命令仍然可以工作如下:

OLDIFS=$IFS; IFS=$'\n'; for line in $(cat peptides.txt); do cmd_a.sh $line; cmd_b.py $line; done > outfile.txt; IFS=$OLDIFS

这只是告诉shell只在换行上拆分,而不是在空格上拆分,然后将环境返回到以前的状态。此时,您可能需要考虑将其全部放入shell脚本,而不是将其全部压缩到一行中。

祝你好运!

还有一些其他答案没有涵盖的问题:

从分隔文件读取

# ':' is the delimiter here, and there are three fields on each line in the file
# IFS set below is restricted to the context of `read`, it doesn't affect any other code
while IFS=: read -r field1 field2 field3; do
  # process the fields
  # if the line has less than three fields, the missing fields will be set to an empty string
  # if the line has more than three fields, `field3` will get all the values, including the third field plus the delimiter(s)
done < input.txt

使用进程替换从另一个命令的输出读取

while read -r line; do
  # process the line
done < <(command ...)

这种方法优于命令…|同时读取-r行;做因为while循环在当前shell中运行,而不是像后者那样在子shell中运行。请参阅相关文章。在while循环内修改的变量不会被记住。

正在从空分隔输入读取,例如find-打印0

while read -r -d '' line; do
  # logic
  # use a second 'read ... <<< "$line"' if we need to tokenize the line
done < <(find /path/to/dir -print0)

相关阅读:BashFAQ/020-如何查找和安全处理包含换行符、空格或两者的文件名?

一次读取多个文件

while read -u 3 -r line1 && read -u 4 -r line2; do
  # process the lines
  # note that the loop will end when we reach EOF on either of the files, because of the `&&`
done 3< input1.txt 4< input2.txt

根据@chepner的回答:

-u是bash扩展。对于POSIX兼容性,每个调用看起来都像read-rX<&3。

将整个文件读入数组(Bash版本早于4)

while read -r line; do
    my_array+=("$line")
done < my_file

如果文件以不完整的行结尾(末尾缺少换行符),则:

while read -r line || [[ $line ]]; do
    my_array+=("$line")
done < my_file

将整个文件读取到阵列中(Bash版本4x及更高版本)

readarray -t my_array < my_file

or

mapfile -t my_array < my_file

然后

for line in "${my_array[@]}"; do
  # process the lines
done

有关shell内置read和readarray命令的更多信息-GNU关于IFS的更多信息-维基百科BashFAQ/001-如何逐行(和/或逐字段)读取文件(数据流、变量)?

相关帖子:

在Bash中从文本文件创建数组两种读取只有一行的文件的方法有什么区别?与猫相比,在读取循环时猛击速度非常慢,为什么?