2

I want to create a script to read a .txt file. This is my code:

while IFS= read -r lines
do
  echo "$lines"
done < <(tail -n +2 filename.txt)

I tried a lot of things like:

<<(tail -n +2 in.txt)
< < (tail -n +2 in.txt)
< (tail -n +2 in.txt)
<(tail -n +2 in.txt)
(tail -n +2 in.txt)

I expected to print me from the second line but instead I get an error:

Syntax error: redirection unexpected
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
F_Stain
  • 33
  • 4

2 Answers2

2

If you just want to ignore the first line, there's no good reason to use tail at all!

{
    read -r first_line
    while IFS= read -r line; do
      printf '%s\n' "$line"
    done
} <filename.txt

Using read to consume the first line leaves the original file pointer intact, so following code can read directly from the file, instead of reading from a FIFO attached to the output of the tail program; it's thus much lower-overhead.


If you did want to use tail, for the specific case raised, you don't need to use a process substitution (<(...)), but can simply pipe into your while loop. Note that this has a serious side effect, insofar as any variables you set in the loop will no longer be available after it exits; this is documented (in a cross-shell manner) in BashFAQ #24.

tail -n +2 filename.txt | while IFS= read -r line
do
  printf '%s\n' "$line"
done
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
1

As it says in this answer POSIX shell equivalent to <() you could use named pipes to simulate process substitution in POSIX. Your script would look like that:

#!/usr/bin/env sh

mkfifo foo.fifo

tail -n +2 filename.txt >foo.fifo &

while IFS= read -r lines
do
    echo "$lines"
done < foo.fifo

rm foo.fifo
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
  • 1
    How do you see this question as not being an outright duplicate of that one? It raises no questions specific to `tail`; it's simply asking the same thing (how to use process substitution in `sh`) more vaguely, without having done the homework to know the terminology. – Charles Duffy May 22 '19 at 11:25
  • Now when you say it I also think it's a duplicate. I didn't think of it as a duplicate because OP doesn't even know why his script fails, he didn't say he has problems with process substitutions. – Arkadiusz Drabczyk May 22 '19 at 11:27