I have been Googling to no avail, so I would appreciate someone's kind help a lot.
I have a string of filenames that will be generated, and each filename is separated by the character |.
For instance, the string of filenames looks similar to:
/home/user/something or other.txt|/home/user/Downloads/something else.txt|/home/somewhere/there are spaces definitely.txt|/home/user/there are always spaces.txt|/home/user/Documents/spaces are always present.txt
I would like to split this string into an array, using the character | to split up the filenames and their locations.
I have tried this:
IFS='|' read -ra array <<< "$string"
but it does NOT work and gives me the following error message:
Syntax error: redirection unexpected
Perhaps someone much more clever than me has the solution? I would greatly appreciate it!
22 Answers
Your code is correct - for bash
I have #!/bin/bash at the top of the .sh file
Good
Then I run sh filename.sh to run it.
Here's the problem - you're explicitly telling the system to ignore the shebang, and run the script with sh. That likely resolves to /bin/sh which on Ubuntu is the POSIX dash shell by default.
Instead, just make your script executable
chmod +x filename.shand then run it using
./filename.shwhich will ensure the correct interpreter is used. See also
3Reading string into an index array with a user defined delimiter using mapfile:
$ string='1|2|3|4'; \ mapfile -td \| <<< $string; echo ${MAPFILE[@]}