W
W
webpixel2015-08-25 19:53:14
bash
webpixel, 2015-08-25 19:53:14

What is the correct regex pattern for grep?

Hello connoisseurs! Please tell me how to correctly compose a pattern for grep, it seems to work, but for some reason it works 2 times.
There are files with such names report_ 20150825 1025.txt
Task:
Search for files containing "report_" and extract the date for further processing.
I get all the files in a loop and I want to get the year, I do:

#!/bin/bash

for file in *; do
  full_date="$(echo $file | grep -o -E 'report_[0-9]{8}')"
  year="$(echo $full_date | grep -o -E '[0-9]{4}')"
  echo $year
done

In response I get:
2015 0825
Why does it work 2 times, where do I make a mistake? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
3
3vi1_0n3, 2015-09-11
@webpixel

You are making a mistake in thinking that grep will stop after finding the first 4 characters. In fact, there will be another match on the same line - the next 4 characters.
And if you just need to get a year, then it’s better like this:

#!/bin/bash

for file in report_*; do
  echo ${file:7:4}
done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question