Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

linux - 在Bash中循环浏览文件内容(Looping through the content of a file in Bash)

How do I iterate through each line of a text file with Bash ?

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

With this script:

(使用此脚本:)

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)'

(Later I want to do something more complicated with $p than just output to the screen.)

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


The environment variable SHELL is (from env):

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

SHELL=/bin/bash

/bin/bash --version output:

(/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 output:

(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

The file peptides.txt contains:

(肽文件.txt文件包含:)

RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL
  ask by Peter Mortensen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way to do it is:

(一种方法是:)

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

Here, 10 is just an arbitrary number (different from 0, 1, 2).

(在这里,10只是一个任意数字(不同于0、1、2)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...