循环遍历Bash中的文件内容 [英] Looping through the content of a file in Bash

查看:148
本文介绍了循环遍历Bash中的文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

(后来我想做一些比{code> $ 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在评论中指出,这具有修剪前导空格,解释反斜杠序列和跳过尾随线的副作用,如果它缺少终止换行符。如果这些是问题,你可以这样做:

As pointed out in the comments, this has the side effects of trimming leading whitespace, interpretting backslash sequences, and skipping the trailing 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\n' "$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中的文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆