Answer the question
In order to leave comments, you need to log in
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
2015 0825
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question