how to loop through the content of a file using bash

0 votes

I want to print each line of a file using bash?

I'm using this script:

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

and I get this output:

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


The environment variable SHELL is (from env):

SHELL=/bin/bash

/bin/bash --version output:

GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.

cat /proc/version output:

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
Feb 15 in Linux Administration by shubham
• 6,890 points
66 views

1 answer to this question.

0 votes

One of the ways to do it is:

while read p; do
  echo "$p"
done <peptides.txt

But this will result in whitespaces, interpretting, backlash sequences getting removed. If you have these concerns then you can try:

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 is just random number here.

answered Feb 15 by ajs3033
• 7,280 points

Related Questions In Linux Administration

0 votes
1 answer
0 votes
1 answer

How to display a simple list of all disks, like this /dev/sda /dev/sdb ?

You can list all the disk in ...READ MORE

answered Jul 12, 2018 in Linux Administration by DearestOne
• 200 points
100 views
0 votes
1 answer
0 votes
1 answer

How to install a deb file?

You can install a .deb file with ...READ MORE

answered Apr 1 in Linux Administration by Shaan
19 views
0 votes
1 answer
0 votes
1 answer

Redirecting output to a file and stdout

The command you want is named tee; foo ...READ MORE

answered May 31 in Linux Administration by Shubham
• 13,290 points
21 views
0 votes
1 answer
0 votes
1 answer

How do I set variable if a specific package version is installed in CFEngine?

Here is what you can do.Just use packagesmatching to ...READ MORE

answered Jul 12, 2018 in Other DevOps Questions by Atul
• 10,240 points
73 views
0 votes
1 answer

redirecting stdout and stderr to file using bash

cmd >>file.txt 2>&1 Bash always executes and redirects ...READ MORE

answered Mar 19 in Linux Administration by ajs3033
• 7,280 points
36 views
0 votes
1 answer

How to collect all output in one file?

You can use 2> to redirect it: foo ...READ MORE

answered Mar 1 in Linux Administration by ajs3033
• 7,280 points
24 views