I'm trying to rename multiple files containing dates. I want to split the date into year, month and day and then create a new filename in a directory tree like year/month-year/filename_yearmonthday.extension

I already succeeded in creating a sed expression to filter out the date and write it back into three separate variables. I would now like to insert the values into an array, where [0] is year, [1] is month and [2] is day. I tried the following statement:

for i in *
myarray=( $(echo ${i} |  \
  sed -n 's/.*\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\).*/\1 \2 \3/p' ) )

but the script complains about Syntax error: "(" unexpected (expecting "done") in the third line containing the sed-expression.

***edit The position of the date keeps changing, so I can't just split by strings.

As of now, I don't even succeed in something like this:

myarray=(1 2 3 4)
echo ${myarray[@]}

it always tells me "Syntax error: "(" unexpected (expecting "done")" in the line containing the array. ***endedit

If I do this directly in the command line, it's working. Thanks for the help.

  • 1
    use /bin/bash if you want a bash script.. regarding syntax error, I think \3)/p' ) should be \3/p' ) ) .. there are other issues in your script as well, such as mywiki.wooledge.org/ParsingLs
    – Sundeep
    Aug 25, 2016 at 11:30
  • Oh, sorry, I lost that bracket in copying. I checked this in my script multiple times. Also sorry for the wrong shebang, am working via ssh and simply got confused as to which I was using (not that it works in bash, either...)
    – bstabens
    Aug 25, 2016 at 14:02
  • do you get syntax error if you remove the if..fi portion of the script? if not, you will have to post the code in if..fi as well
    – Sundeep
    Aug 25, 2016 at 14:20
  • No, same thing without the if.
    – bstabens
    Aug 26, 2016 at 4:13
  • well, I don't get any syntax error.. you can try out shellcheck.net/#
    – Sundeep
    Aug 26, 2016 at 4:16

1 Answer 1


If it were me, I would load up the array like this:




echo "${myarray[0]}"
echo "${myarray[1]}"
echo "${myarray[2]}"
  • They keep moving the date around, so no luck in splitting by character position.
    – bstabens
    Aug 26, 2016 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.