Looping through the content of a file in Bash

后端 未结 13 2382
傲寒
傲寒 2020-11-21 10:08

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

With this script:

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


        
13条回答
  •  时光说笑
    2020-11-21 10:41

    One way to do it is:

    while read p; do
      echo "$p"
    done 

    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\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

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

提交回复
热议问题