I want to make a directory name by extracting parts of a file name. Here are some examples:

  1. server.log.2016-03-20-1420160320
  2. server-2016-03-17-13-16-Restart.log20160317

I'm using HP-UX.


You could use awk for it.


echo server.log.2016-03-20-14 | awk -F'[.]' '{print $3}' | awk -F'[-]' '{print $1$2$3}'


echo server-2016-03-17-13-16-Restart.log | awk -F'[-]' '{print $2$3$4}'
| improve this answer | |

You can pass filename to regex check, with sed:

echo server.log.2016-03-20-14 | sed 's/server\.log\.\([0-9]\{4\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)/\1\2\3/g'

echo server-2016-03-17-13-16-Restart.log | sed 's/server-\([0-9]\{4\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)-Restart.log/\1\2\3/g'

If you need more strict regex, for example months can be described with regex


and days are

| improve this answer | |

You can do this with the shell's string manipulation constructs. This requires a POSIX shell, so if you're running an ancient version of HP-UX you may need to call a POSIX shell such as ksh rather than the Bourne shell.

You didn't fully specify how to parse the date. I'm assuming that the first match of ????-??-?? where each of the ?? are digits is the date you want.

s=${0#"$p"}; p=${0%"$p"}
year=${p%??????}; p=${p#?????}
month=${p%???}; day=${p#???}
echo "$year$month$day"

Not the most readable code but it works.

| improve this answer | |

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.