-1

I'm using the following command to get the year out of a string using sed.

echo 1234-1-12 | sed -r 's/(\d{4})-\d{1,2}-\d{1,2}/\1/'

but somehow it returns the entire date instead of the year.

getting 1234-1-12

expecting 1234

Any ideas why it doesn't work?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Pat
  • 23
  • 3

2 Answers2

0

Simple grep approach:

echo "1234-1-12" | grep -o '^[^-]*'

The output:

1234
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

Use the date command:

string="1234-1-12"
date -d "${string}" +%Y

Output:

1234
hek2mgl
  • 152,036
  • 28
  • 249
  • 266