On Mon, Feb 20, 2023 at 07:10:11AM +0000, Albretch Mueller wrote:
> On 2/15/23, Greg Wooledge <g...@wooledge.org> wrote:
> > If you want to read FIELDS of a SINGLE LINE as array elements, use
> > read -ra:
> >
> > read -ra myarray <<< "$one_line"
> 
>  It didn't work. I tried different options. I am getting: "bash: read:
> ... : not a valid identifier"
> 
>  _PTH="83847547|2|dli.ernet.449320/449320-Seduction Of The Innocent_text.pdf"
>  echo "// __ \$_PTH: \"${_PTH}\""
> 
> # read -ra -d "\\|" _PTH_AR <<< "${_PTH}"
> # read -ra -d "\|" _PTH_AR <<< "${_PTH}"
> # read -ra -d "|" _PTH_AR <<< "${_PTH}"

The -a option has to be followed by the array name.  The -d option has
to be followed by the delimiter.

However, you do NOT want -d "|" here.  The -d delimiter tells read
where to stop reading entirely.  For you, that's the newline character,
which is the default for read, and which is added by the <<< operator.

If you wish to do field splitting when using read, that's what IFS is
for.  However, beware of the atrociously stupid pitfall regarding IFS
with non-whitespace values.

unicorn:~$ _PTH="83847547|2|dli.ernet.449320/449320-Seduction Of The 
Innocent_text.pdf"
unicorn:~$ declare -p _PTH
declare -- _PTH="83847547|2|dli.ernet.449320/449320-Seduction Of The 
Innocent_text.pdf"
unicorn:~$ IFS="|" read -ra _PTH_AR <<< "${_PTH}|"
unicorn:~$ declare -p _PTH_AR
declare -a _PTH_AR=([0]="83847547" [1]="2" 
[2]="dli.ernet.449320/449320-Seduction Of The Innocent_text.pdf")

That, I believe, is what you were trying to accomplish.  Note that I
added a trailing | character on the <<< "${_PTH}|" command.  That's
because of this pitfall:

https://mywiki.wooledge.org/BashPitfalls#pf47

Now we just need to teach you to stop using _ALL_CAPS variable names,
especially ones with leading underscores.

Reply via email to