This is wrong.
farray=(echo $filename | cut -d\/ -f-1)
The array setting pattern is arrayname=()
. The brackets should contain a list of words to set the elements to. As it is, your list of words is: "echo
", etc., with the "|" causing a syntax error.
What you need is to use a command substitution
to generate a list of words from the command first. The syntax for that is $(..)
Also, the command you'd usually want to use to break up a string is tr
. The following converts the filename four separate "words", which will then be placed into individual array indexes:
farray=( $( echo "$filename" | tr '/' ' ' ) )
There are other, and better, ways to break up a string into an array too. See here:
The second link is to another recent post by me on the same topic.
Note that since the array stores a list of the separate elements without the delimiters
, if you wanted to print out the "pathname" you'd have to use something like this:
But all this is an overly-complex way to get what you want. What you really need is to use either the dirname
commands, or parameter substitution
, as crts has already demonstrated.
By the way, cut can
do what you want, within limits. But you have to be clear on how it works. If you have a look at the man page you'll see that "-M
" is the same as "1-M
", so in the above command you were asking it to print only
the first field.
There's yet another issue however that's less obvious. When you set a delimiter to something other than the default, and the delimiting character happens to fall at the start of the string, then the actual first field is null space in front of it
echo "$filename" | cut -d'/' -f 1
...means it prints what comes before the first "/", which is "nothing".
The same thing happens at the other end of the string too, by the way. If the final character is the delimiter, then the last field will also be an empty field.
is limited in that you can only tell it to print a fixed number of strings, and you can only specify one set of fields in a single command. So you can use, for example...
echo "$filename" | cut -d'/' -f 1-4
echo "$filename" | cut -d '/' -f 5
...to get what you want. But what happens if the input filepath has 5 levels? Or 3?