0

I am trying to extract a pattern in shell script.I have the below variable with date format(yyyyMMdd) has value.

field=20200825

Here i want to extract the date,month,year. In case of months if 0 is prefixed, for e.g if 08 is there i need only 8 to be extracted from it.

Can anybody help me on this?

2 Answers2

0

An example script, extracts y/m/d info from string based on offset + length, and trim a possible leading '0' from month

#!/bin/bash

field=20200825
year=${field:0:4}
month=${field:4:2}
month=${month#0}
day=${field:6:2}

echo year $year
echo month $month
echo day $day
Milag
  • 1,793
  • 2
  • 9
  • 8
0

As @Milag answered, you can use Substring Expansion to cut your needed variables. This is true because you said in a comment that you are using bash.

If you need a more portable way to do it, you can (among other solutions) use printf formatting:

#!/bin/sh
field=20200826
year="$(printf "%.4s" "${field}")"
field="${field#????}"
month="$(printf "%.2s" "${field}")"
month="${month#0}"
day="${field#??}"
printf 'year: %s\n' "${year}"
printf 'month: %s\n' "${month}"
printf 'day: %s\n' "${day}"
ingroxd
  • 995
  • 1
  • 12
  • 28