1

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.

1

You could use awk for it.

1)

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

2)

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

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

0[0-9]\|1[12]

and days are

0[1-9]\|[12][0-9]\|3[01]
0

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.

p=${0#*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]}
s=${0#"$p"}; p=${0%"$p"}
p=${p#"${p%??????????}"}
year=${p%??????}; p=${p#?????}
month=${p%???}; day=${p#???}
echo "$year$month$day"

Not the most readable code but it works.

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.