2

Trying to read nth line from file and split in to array based on delimiter

HEAD_START=4
IFS='|' read -r -a headers < sed "${HEAD_START}q;d" "/FILE_UPLOADS/Checklist-Relationship (4).txt"

The above gives "sed: cannot open [No such file or directory]"

But when i run just sed "${HEAD_START}q;d" "/FILE_UPLOADS/Checklist-Relationship (4).txt" in the prompt it works fine

2 Answers 2

5

read -r -a headers < sed ... is trying to open a file named sed for reading.

In bash, to run sed as a command and make its output available on the standard input stream, you can use a process substitution:

IFS='|' read -r -a headers < <(sed "${HEAD_START}q;d" "/FILE_UPLOADS/Checklist-Relationship (4).txt")
5
  • Thanks. Code: IFS='|' read -r -a headers < <(sed "${HEAD_START}q;d" "/FILE_UPLOADS/Checklist-Relationship (4).txt") and the error i am getting now is read: -a: unknown option Usage: read [-ACprsSv] [-d delim] [-u fd] [-t timeout] [-n count] [-N count] [var?prompt] [var ...] Commented Sep 8, 2022 at 4:56
  • @Pat are you actually using ksh rather than bash? Commented Sep 8, 2022 at 11:43
  • i think yes, i am using ksh Commented Sep 8, 2022 at 12:13
  • 1
    @Pat in that case, you will need to use -A in place of -a in the builtin read command - see for example Read first line split based on delimiter and store it in array (in ksh) Commented Sep 8, 2022 at 12:18
  • works and thanks Commented Sep 8, 2022 at 13:56
3

If the file is not too big, I'd skip sed:

mapfile -t lines < filename
IFS='|' read -ra headers <<< "${lines[HEAD_START - 1]}"

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.