2041

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

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


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

The file peptides.txt contains:

RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL
Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 43
    Oh, I see many things have happened here: all the comments were deleted and the question being reopened. Just for reference, the accepted answer in [Read a file line by line assigning the value to a variable](http://stackoverflow.com/a/10929511/1983854) addresses the problem in a canonical way and should be preferred over the accepted one here. – fedorqui Aug 30 '16 at 09:44
  • for `$IFS` see [What is the exact meaning of `IFS=$'\n'`](https://stackoverflow.com/questions/4128235/what-is-the-exact-meaning-of-ifs-n/66942306#66942306) – Peyman Mohamadpour Apr 04 '21 at 21:53
  • don't use bash use `awk` https://www.gnu.org/software/gawk/manual/gawk.html – Chris Feb 16 '22 at 16:07

16 Answers16

2856

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

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

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Bruno De Fraine
  • 45,466
  • 8
  • 54
  • 65
  • 13
    How should I interpret the last line? File peptides.txt is redirected to standard input and somehow to the whole of the while block? – Peter Mortensen Oct 05 '09 at 18:16
  • 14
    "Slurp peptides.txt into this while loop, so the 'read' command has something to consume." My "cat" method is similar, sending the output of a command into the while block for consumption by 'read', too, only it launches another program to get the work done. – Warren Young Oct 05 '09 at 18:30
  • This didn't work for me. The second ranked answer, which used cat and a pipe, did work for me. – Karl Katzke Jul 30 '13 at 16:27
  • 12
    This method seems to skip the last line of a file. – xastor Nov 07 '13 at 07:48
  • Can this be done in reverse starting at the bottom of the file? – Dss Jan 14 '14 at 16:53
  • @Dss Then I would use a solution based on `cat` but replace `cat` by `tac`. – Bruno De Fraine Jan 16 '14 at 09:28
  • @BrunoDeFraine I've tried that but tac seems to make each space a new line. I need the full line delimited by the newline char. maybe I'm doing it wrong. – Dss Jan 16 '14 at 14:58
  • @BrunoDeFraine Ok I found this: http://unix.stackexchange.com/a/7012 ..change cat to tac and it works. Thanks! – Dss Jan 16 '14 at 16:38
  • @Dss I meant the solution from Warren Young http://stackoverflow.com/a/1521470/6918 ; just replace cat by tac and you should read the lines in reverse. – Bruno De Fraine Jan 16 '14 at 19:25
  • 7
    Double quote the lines !! echo "$p" and the file.. trust me it will bite you if you don't!!! I KNOW! lol – Mike Q Aug 19 '14 at 17:01
  • 29
    Both versions fail to read a final line if it is not terminated with a newline. **Always** use `while read p || [[ -n $p ]]; do ...` – dawg Sep 07 '16 at 14:15
  • This does not work for lines that end with a backslash "\". Lines ending with a backslash will be prepended to the next line (and the \ will be removed). – Veda Jan 17 '17 at 11:11
  • @Veda Now that's weird. What I would expect is, you get an extra `n` after the backslash, and the lines get concatenated. Because that would mean, the backslash escapes the backslash of `\n`, causing it to be interpreted literally rather than as a newline. But the fact that the backslash disappears, as well as the newline, means it's consumed for some kind of escaping like expected, but gets merged with the original newline character into something that isn't printed... Do you have a tool that displays unprinted characters in some way? Would interest me what that results in. – Egor Hans Nov 12 '17 at 14:37
  • @EgorHans the \ escapes the "\n" character which is a single character. Google for an "ascii table". Character 10 is \n and character 13 is \r. Linux "xxd" tool will show you the characters. A file with `a\na\n\\n` will look like: `610a 610a 5c0a` (0a is hex for 10, so \n). So the last case the "5c" character or the "\" is escaping a single character. – Veda Nov 13 '17 at 15:32
  • @Veda Ah OK, now I understand better. Didn't realize the file content gets dumped into the execution flow the way it's inside the file, where of course `\n` is one single character. For some reason I've been thinking it gets backresolved to the control sequence while processed. Still, it's somewhat weird that an escaped `\n` is something without a printed representation. One would expect it to resolve to the char sequence "\n" when escaped. – Egor Hans Nov 14 '17 at 16:30
  • Your soul be blessed for that different file descriptor command, made me happy, wasted 8 days on an error generated by standard input replacement. +1 – Shmiggy Oct 03 '18 at 12:21
  • can you please mention what the `-r` flag does? – Alexander Mills Jun 04 '19 at 06:33
  • @AlexanderMills `-r` disables the interpretation of backslashes as escape sequences. The empty `IFS` disables that `read` splits up the line in fields. And because `read` fails when it encounters end-of-file before the line ends, we also test for a non-empty line. – Bruno De Fraine Jun 05 '19 at 07:13
  • `read` is ignoring the `\r` character when the file uses windows line endings (i.e. `\r\n`). How can I make `read` treat `\r` as part of the newline sequence? – void.pointer Aug 02 '19 at 16:27
  • If you are like me and you do these things in the shell in a single line, you need to add another semi-colon like so: while read p; do echo "$p"; done – Kramer Oct 25 '19 at 17:04
750
cat peptides.txt | while read line 
do
   # do something with $line here
done

and the one-liner variant:

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

These options will skip the last line of the file if there is no trailing line feed.

You can avoid this by the following:

cat peptides.txt | while read line || [[ -n $line ]];
do
   # do something with $line here
done
rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Warren Young
  • 40,875
  • 8
  • 85
  • 101
  • 95
    In general, if you're using "cat" with only one argument, you're doing something wrong (or suboptimal). – JesperE Oct 05 '09 at 18:02
  • 34
    Yes, it's just not as efficient as Bruno's, because it launches another program, unnecessarily. If efficiency matters, do it Bruno's way. I remember my way because you can use it with other commands, where the "redirect in from" syntax doesn't work. – Warren Young Oct 05 '09 at 18:12
  • 94
    There's another, more serious problem with this: because the while loop is part of a pipeline, it runs in a subshell, and hence any variables set inside the loop are lost when it exits (see http://bash-hackers.org/wiki/doku.php/mirroring/bashfaq/024). This can be very annoying (depending on what you're trying to do in the loop). – Gordon Davisson Oct 06 '09 at 00:57
  • 1
    @JesperE would you care to elaborate with an alternative example? – Ogre Psalm33 Nov 21 '11 at 16:35
  • 1
    @Ogre: He means you should be doing it like Bruno did in his accepted answer. Both work. Bruno's way is just a bit more efficient, since it doesn't run an external command to do the file reading bit. If the efficiency matters, do it Bruno's way. If not, then do it whatever way makes the most sense to you. – Warren Young Nov 21 '11 at 16:37
  • 3
    @OgrePsalm33: Warren is right. The "cat" command is used for concatenating files. If you are not concatenating files, chances are that you don't need to use "cat". – JesperE Nov 22 '11 at 10:38
  • 2
    Ok, makes sense. I wanted to make a point of it because I see a lot of overused examples in scripts and such, where "cat" simply serves as an extra step to get the contents of a single file. – Ogre Psalm33 Nov 22 '11 at 21:43
  • 34
    I use "cat file | " as the start of a lot of my commands purely because I often prototype with "head file |" – mat kelcey Feb 26 '14 at 21:33
  • 4
    @matkelcey Also, how else would you put an entire file into the front of a pipeline? Bash gives you here strings, which are awesome (especially for things like `if grep -q 'findme' <<< "$var"`) but not portable, and I wouldn't want to start a large pipeline with one. Something like `cat ifconfig.output | grep inet[^6] | grep -v '127.0.0.1' | awk '{print $2}' | cut -d':' -f2` is easier to read, since everything follows from left to right. It's like strtoking with `awk` instead of `cut` because you don't want empty tokens - it's sort of an abuse of the command, but that's just how it's done. – ACK_stoverflow Jun 18 '14 at 19:25
  • 107
    This may be not that efficient, but it's much more readable than other answers. – Savage Reader Dec 22 '14 at 13:02
  • 4
    +1 for readability, and also modularity - this code can easily be put into a more complex pipeline by replacing 'cat ...' with output of something else. – tishma Sep 03 '15 at 09:59
  • 2
    It is much better resolve than Bruno has written. It is specially usefull when data is created dynamically by command. Using Bruno's solution, loop will receive any data after command will completly done. Your solution gives command result on line into loop, without taking buffer from system. for example replace 'cat peptides.txt' by 'find /', or in previous solution 'done – Znik Nov 27 '15 at 12:42
  • 8
    By the time you care about the difference in performance you won't be asking SO these sorts of questions. – Ryan Feb 28 '18 at 01:20
  • This is, however, great for grep, sed, or any other text manipulation prepending the read. – Cory Ringdahl Aug 29 '18 at 00:27
  • this does not work if any of the commands inside your loop run commands via ssh; the stdin stream gets consumed (even if ssh is not using it), and the loop terminates after the first iteration. – user5359531 Nov 12 '18 at 22:58
  • 1
    As in the accepted answer, this will have unpleasant surprises without `read -r` in some corner cases. Basically always use `read -r` unless you specifically require the quirky behavior of plain legacy `read`. – tripleee Jan 30 '19 at 18:38
  • 2
    It skips the last line. So as workaround, must add empty line at the last. – januarvs Apr 18 '19 at 21:41
  • 1
    @januarvs: It only does that if the last line of your file has no LF terminator, which will cause lots of other things to fail, too. – Warren Young Apr 19 '19 at 02:43
  • 1
    @GordonDavisson Your link is broken, the new one is : https://mywiki.wooledge.org/BashFAQ/024 – Nino DELCEY May 19 '22 at 15:06
  • This is [UUOC](https://en.wikipedia.org/wiki/Cat_(Unix)#Useless_use_of_cat). – Michael Hall Mar 01 '23 at 01:09
  • I like this approach more because it is easier to understand and you can easily replace `cat` part with anything that generates stdout output. – xiay Mar 15 '23 at 18:52
236

Option 1a: While loop: Single line at a time: Input redirection

#!/bin/bash
filename='peptides.txt'
echo Start
while read p; do 
    echo "$p"
done < "$filename"

Option 1b: While loop: Single line at a time:
Open the file, read from a file descriptor (in this case file descriptor #4).

#!/bin/bash
filename='peptides.txt'
exec 4<"$filename"
echo Start
while read -u4 p ; do
    echo "$p"
done
tripleee
  • 175,061
  • 34
  • 275
  • 318
Stan Graves
  • 6,795
  • 2
  • 18
  • 14
  • For option 1b: does the file descriptor need to be closed again? E.g. the loop could be an inner loop. – Peter Mortensen Oct 05 '09 at 20:03
  • 4
    The file descriptor will be cleaned up with the process exits. An explicit close can be done to reuse the fd number. To close a fd, use another exec with the &- syntax, like this: exec 4<&- – Stan Graves Oct 05 '09 at 21:09
  • 1
    Thank you for Option 2. I ran into huge problems with Option 1 because I needed to read from stdin within the loop; in such a case Option 1 will not work. – masgo Jun 04 '14 at 13:50
  • 4
    You should point out more clearly that Option 2 is [strongly discouraged](http://mywiki.wooledge.org/DontReadLinesWithFor). @masgo Option 1b should work in that case, and can be combined with the input redirection syntax from Option 1a by replacing `done < $filename` with `done 4<$filename` (which is useful if you want to read the file name from a command parameter, in which case you can just replace `$filename` by `$1`). – Egor Hans Nov 12 '17 at 16:44
  • I need to loop over file contents such as `tail -n +2 myfile.txt | grep 'somepattern' | cut -f3`, while running ssh commands inside the loop (consumes stdin); option 2 here appears to be the only way? – user5359531 Nov 12 '18 at 23:21
  • Option 2 seems to be the best when some actions should be performed on remote host via SSH. – Vladimir Sh. Jul 23 '19 at 08:35
  • 1a for me is fine as soon as One add "echo $p" at end (last line from file) – Virtimus Jan 10 '21 at 09:35
  • upvoted for showing the example of a filename as a variable. Thanks! – parkerfath Aug 24 '23 at 17:10
150

This is no better than other answers, but is one more way to get the job done in a file without spaces (see comments). I find that I often need one-liners to dig through lists in text files without the extra step of using separate script files.

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

This format allows me to put it all in one command-line. Change the "echo $word" portion to whatever you want and you can issue multiple commands separated by semicolons. The following example uses the file's contents as arguments into two other scripts you may have written.

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

Or if you intend to use this like a stream editor (learn sed) you can dump the output to another file as follows.

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

I've used these as written above because I have used text files where I've created them with one word per line. (See comments) If you have spaces that you don't want splitting your words/lines, it gets a little uglier, but the same command still works as follows:

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

This just tells the shell to split on newlines only, not spaces, then returns the environment back to what it was previously. At this point, you may want to consider putting it all into a shell script rather than squeezing it all into a single line, though.

Best of luck!

mightypile
  • 7,589
  • 3
  • 37
  • 42
  • 1
    This doesn't meet the requirement (iterate through each line) if the file contains spaces or tabs, but can be useful if you want to iterate through each field in a tab/space separated file. – Joao Costa Oct 30 '13 at 12:37
  • 6
    The bash $( – maxpolk Dec 08 '13 at 17:58
  • 2
    @JoaoCosta,maxpolk : Good points that I hadn't considered. I've edited the original post to reflect them. Thanks! – mightypile Dec 22 '13 at 15:49
  • 3
    Using `for` makes the input tokens/lines subject to shell expansions, which is usually undesirable; try this: `for l in $(echo '* b c'); do echo "[$l]"; done` - as you'll see, the `*` - even though originally a *quoted* literal - expands to the files in the current directory. – mklement0 Dec 22 '13 at 16:09
  • Joao and maxpolk, you are addressing the issue I'm having, but I'm still getting a separate iteration for each half of each line with a space: > cat linkedin_OSInt.txt https://www.linkedin.com/vsearch/f?type=all&keywords="foo bar" https://www.linkedin.com/vsearch/f?type=all&keywords="baz bux" > for url in $( – dblanchard Nov 13 '15 at 19:18
  • 2
    @dblanchard: The last example, using $IFS, should ignore spaces. Have you tried that version? – mightypile Nov 24 '15 at 00:53
  • please notice for changing cat peptides.txt by find / . for loop will not start before internal cat finishes. between these steps it is possible buffer overflow. – Znik Nov 27 '15 at 12:44
  • 5
    The way how this command gets a lot more complex as crucial issues are fixed, presents very well why using `for` to iterate file lines is a a bad idea. Plus, the expansion aspect mentioned by @mklement0 (even though that probably can be circumvented by bringing in escaped quotes, which again makes things more complex and less readable). – Egor Hans Nov 12 '17 at 14:23
  • 1
    This is, in a readable way, the only answer that also reads the latest line of a file, which is a pro. – David Tabernero M. Jun 07 '18 at 23:07
  • 1
    This answer is exactly what I need. The other answers that use while to iterate over lines or ok when one wants to deal with lines of text. But I'd use Python for that. In a shell I often have files containing hundreds of items that will be treated as tokens. I need the removal of newlines, which this syntax provides. Thanks for the answer. – All The Rage Nov 03 '20 at 04:11
  • No need in OLDIFS if use subshell-parentheses () around `IFS=$'\n'; for ...; done` – vatosarmat May 16 '21 at 12:42
111

A few more things not covered by other answers:

Reading from a delimited file

# ':' 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

Reading from the output of another command, using process substitution

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

This approach is better than command ... | while read -r line; do ... because the while loop here runs in the current shell rather than a subshell as in the case of the latter. See the related post A variable modified inside a while loop is not remembered.

Reading from a null delimited input, for example find ... -print0

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)

Related read: BashFAQ/020 - How can I find and safely handle file names containing newlines, spaces or both?

Reading from more than one file at a time

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

Based on @chepner's answer here:

-u is a bash extension. For POSIX compatibility, each call would look something like read -r X <&3.

Reading a whole file into an array (Bash versions earlier to 4)

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

If the file ends with an incomplete line (newline missing at the end), then:

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

Reading a whole file into an array (Bash versions 4x and later)

readarray -t my_array < my_file

or

mapfile -t my_array < my_file

And then

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

Related posts:

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • note that instead of `command < input_filename.txt` you can always do `input_generating_command | command` or `command < <(input_generating_command)` – masterxilo Mar 07 '19 at 14:00
  • 1
    Thanks for reading file into array. Exactly what I need, because I need each line to parse twice, add to new variables, do some validations etc. – frank_108 Mar 06 '20 at 15:06
  • 1
    this is by far the most useful version I think – user5359531 Jun 24 '20 at 18:21
  • 'read -r -d ''` works for null delimited input in combination with `while`, not standalone (`read -r d '' foo bar`). See [here](https://unix.stackexchange.com/questions/693090/splitting-a-null-separated-string). – Erwann Mar 19 '22 at 22:42
52

Use a while loop, like this:

while IFS= read -r line; do
   echo "$line"
done <file

Notes:

  1. If you don't set the IFS properly, you will lose indentation.

  2. You should almost always use the -r option with read.

  3. Don't read lines with for

Jahid
  • 21,542
  • 10
  • 90
  • 108
  • 3
    @DavidC.Rankin The -r option prevents backslash interpretation. `Note #2` is a link where it is described in detail... – Jahid Jun 23 '15 at 06:01
  • Combine this with the "read -u" option in another answer and then it's perfect. – Florin Andrei Feb 17 '17 at 00:06
  • @FlorinAndrei : The above example doesn't need the `-u` option, are you talking about another example with `-u`? – Jahid Feb 17 '17 at 05:37
  • Looked through your links, and was surprised there's no answer that simply links your link in Note 2. That page provides everything you need to know about that subject. Or are link-only answers discouraged or something? – Egor Hans Nov 12 '17 at 16:49
  • @EgorHans : link only answers are generally deleted. – Jahid Nov 13 '17 at 02:00
  • Ah. Alright, never suggesting a link-only answer again. Maybe there even were some, we'll never know. – Egor Hans Nov 14 '17 at 16:34
18

If you don't want your read to be broken by newline character, use -

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "$line"
done < "$1"

Then run the script with file name as parameter.

Anjul Sharma
  • 189
  • 1
  • 3
  • Note to self: the '-r' option 'prevents backslash interpretation'; http://mywiki.wooledge.org/BashFAQ/001 – muthuh Jul 26 '23 at 12:19
17

Suppose you have this file:

$ cat /tmp/test.txt
Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR

There are four elements that will alter the meaning of the file output read by many Bash solutions:

  1. The blank line 4;
  2. Leading or trailing spaces on two lines;
  3. Maintaining the meaning of individual lines (i.e., each line is a record);
  4. The line 6 not terminated with a CR.

If you want the text file line by line including blank lines and terminating lines without CR, you must use a while loop and you must have an alternate test for the final line.

Here are the methods that may change the file (in comparison to what cat returns):

1) Lose the last line and leading and trailing spaces:

$ while read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'

(If you do while IFS= read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt instead, you preserve the leading and trailing spaces but still lose the last line if it is not terminated with CR)

2) Using process substitution with cat will reads the entire file in one gulp and loses the meaning of individual lines:

$ for p in "$(cat /tmp/test.txt)"; do printf "%s\n" "'$p'"; done
'Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR'

(If you remove the " from $(cat /tmp/test.txt) you read the file word by word rather than one gulp. Also probably not what is intended...)


The most robust and simplest way to read a file line-by-line and preserve all spacing is:

$ while IFS= read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'    Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space    '
'Line 6 has no ending CR'

If you want to strip leading and trading spaces, remove the IFS= part:

$ while read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'
'Line 6 has no ending CR'

(A text file without a terminating \n, while fairly common, is considered broken under POSIX. If you can count on the trailing \n you do not need || [[ -n $line ]] in the while loop.)

More at the BASH FAQ

dawg
  • 98,345
  • 23
  • 131
  • 206
13

I like to use xargs instead of while. xargs is powerful and command line friendly

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

With xargs, you can also add verbosity with -t and validation with -p

elghazal-a
  • 582
  • 1
  • 8
  • 15
  • There are serious security problems with this approach. What if your `peptides.txt` contains something that unescapes to `$(rm -rf ~)`, or even worse, `$(rm -rf ~)'$(rm -rf ~)'`? – Charles Duffy May 01 '22 at 13:54
12

This might be the simplest answer and maybe it don't work in all cases, but it is working great for me:

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

if you need to enclose in parenthesis for spaces:

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

Ahhh this is pretty much the same as the answer that got upvoted most, but its all on one line.

Jieiku
  • 489
  • 4
  • 15
6
#!/bin/bash
#
# Change the file name from "test" to desired input file 
# (The comments in bash are prefixed with #'s)
for x in $(cat test.txt)
do
    echo $x
done
0zkr PM
  • 825
  • 9
  • 11
Sine
  • 127
  • 1
  • 2
  • 8
    This answer needs the caveats mentioned in [mightypile's answer](/q/1521462/#19182518), and it can fail badly if any line contains shell metacharacters (due to the unquoted "$x"). – Toby Speight Jun 08 '15 at 16:32
  • 9
    I'm actually surprised people didn't yet come up with the usual [Don't read lines with for](http://mywiki.wooledge.org/DontReadLinesWithFor)... – Egor Hans Nov 12 '17 at 14:17
  • This really doesn't work in any general way. Bash splits each line on spaces which is very unlikely a desired outcome. – ingyhere Jun 11 '21 at 21:55
3

Here is my real life example how to loop lines of another program output, check for substrings, drop double quotes from variable, use that variable outside of the loop. I guess quite many is asking these questions sooner or later.

##Parse FPS from first video stream, drop quotes from fps variable
## streams.stream.0.codec_type="video"
## streams.stream.0.r_frame_rate="24000/1001"
## streams.stream.0.avg_frame_rate="24000/1001"
FPS=unknown
while read -r line; do
  if [[ $FPS == "unknown" ]] && [[ $line == *".codec_type=\"video\""* ]]; then
    echo ParseFPS $line
    FPS=parse
  fi
  if [[ $FPS == "parse" ]] && [[ $line == *".r_frame_rate="* ]]; then
    echo ParseFPS $line
    FPS=${line##*=}
    FPS="${FPS%\"}"
    FPS="${FPS#\"}"
  fi
done <<< "$(ffprobe -v quiet -print_format flat -show_format -show_streams -i "$input")"
if [ "$FPS" == "unknown" ] || [ "$FPS" == "parse" ]; then 
  echo ParseFPS Unknown frame rate
fi
echo Found $FPS

Declare variable outside of the loop, set value and use it outside of loop requires done <<< "$(...)" syntax. Application need to be run within a context of current console. Quotes around the command keeps newlines of output stream.

Loop match for substrings then reads name=value pair, splits right-side part of last = character, drops first quote, drops last quote, we have a clean value to be used elsewhere.

Whome
  • 10,181
  • 6
  • 53
  • 65
  • 3
    While the answer is correct, I do understand how it ended up down here. The essential method is the same as proposed by many other answers. Plus, it completely drowns in your FPS example. – Egor Hans Nov 12 '17 at 14:14
2

This is coming rather very late, but with the thought that it may help someone, i am adding the answer. Also this may not be the best way. head command can be used with -n argument to read n lines from start of file and likewise tail command can be used to read from bottom. Now, to fetch nth line from file, we head n lines, pipe the data to tail only 1 line from the piped data.

   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
madD7
  • 823
  • 10
  • 23
  • 6
    **Don't do this.** Looping over line numbers and fetching each individual line by way of `sed` or `head` + `tail` is **incredibly** inefficient, and of course begs the question why you don't simply use one of the other solutions here. If you need to know the line number, add a counter to your `while read -r` loop, or use `nl -ba` to add a line number prefix to each line before the loop. – tripleee Feb 07 '20 at 09:44
  • See also now https://stackoverflow.com/questions/65538947/counting-lines-or-enumerating-line-numbers-so-i-can-loop-over-them-why-is-this – tripleee Aug 11 '21 at 06:08
  • @tripleee i have clearly mentioned "this may not be the best way". I have not limited the discussion to "the best or the most efficient solution". – madD7 Oct 21 '21 at 08:46
  • Iterating over the lines of a file with a for loop can be useful in some situations. For example some commands can make a while loop break. See https://stackoverflow.com/a/64049584/2761700 – scandel Apr 01 '22 at 12:34
  • @tripleee `read` itself is *already* ridiculously slow. In scenarios with very long lines, this solution can likely be faster, so your performance argument doesn't necessarily count. Also see: https://stackoverflow.com/questions/13762625 – phil294 Aug 26 '23 at 19:03
  • @phil294 Reading and discarding the same data over and over is O(n^2) which will be slower than the O(n) `read` in a loop in pretty much all scenarios where it matters at all. The linked question from my second comment has more details. – tripleee Aug 26 '23 at 19:37
1

@Peter: This could work out for you-

echo "Start!";for p in $(cat ./pep); do
echo $p
done

This would return the output-

Start!
RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL
  • 12
    This is very bad! [Why you don't read lines with "for"](http://mywiki.wooledge.org/DontReadLinesWithFor). – fedorqui Jun 16 '16 at 10:43
  • 3
    This answer is defeating all the principles set by the good answers above! – codeforester Jan 14 '17 at 02:55
  • 3
    Please delete this answer. – dawg May 02 '17 at 17:18
  • 5
    Now guys, don't exaggerate. The answer is bad, but it seems to work, at least for simple use cases. As long as that's provided, being a bad answer doesn't take away the answer's right to exist. – Egor Hans Nov 12 '17 at 14:08
  • 4
    @EgorHans, I disagree strongly: The point of answers is to teach people how to write software. Teaching people to do things in a way that you *know* is harmful to them and the people who use their software (introducing bugs / unexpected behaviors / etc) is knowingly harming others. An answer known to be harmful has no "right to exist" in a well-curated teaching resource (and curating it is exactly what we, the folks who are voting and flagging, are supposed to be doing here). – Charles Duffy Sep 20 '18 at 16:36
  • 2
    @EgorHans, ...incidentally, the worst data-loss incident I've been personally witness to was caused by ops staff doing something that "seemed to work" in a script (using an unquoted expansion for a filename to be deleted -- when that name was supposed to be able to contain only hex digits). Except a bug in a different piece of software wrote a name with random contents, which had a whitespace-surrounded `*`, and a massive trove of billing-data backups was lost. – Charles Duffy Sep 20 '18 at 16:40
  • This will work in some cases, but proposed solution is far from good. – Vladimir Sh. Jul 23 '19 at 08:40
0

Another way to go about using xargs

<file_name | xargs -I {} echo {}

echo can be replaced with other commands or piped further.

abhishek nair
  • 324
  • 1
  • 6
  • 18
-1

for p in `cat peptides.txt` do echo "${p}" done

mazman
  • 17
  • 1