0

I have a txt file like this:

./201709.15.txt:88:word word TAG201709152000 word word
./201709.19.txt:3:word TAG201709152000 word word
./201710.10.txt:5:word word TAG201709152000 word word word

and I need to filter only the lines as:

./201709.15.txt:88:word word TAG201709152000 word word

(i.e. with the same date at the beginning: ./YYYMM.dd.txt and after TAG: TAGYYYYMMddhhmm)

Is it possible with shell script?

3
  • 1
    the 3rd item 2017010 does not correspond YYYMM. typo? Oct 16, 2017 at 12:24
  • Even if the last line in your example ./2017010.10 would be correct, it'd be a different date. What part do you want to be matched? Oct 16, 2017 at 12:31
  • @RomanPerekhrest I corrected the typo (it was 201710) Oct 16, 2017 at 13:37

2 Answers 2

3

One way to do it:

grep -E '/([0-9]{6})\.([0-9]{2}).* TAG\1\2' file
1
  • Good solution. Two remarks: 1) Backreferences are not required by the extended regular expressions standard , so this may not work with all versions of grep. Use grep '/\([0-9]\{6\}\)\.\([0-9]\{2\}\).* TAG\1\2' file instead (although it's less readable). 2) Are you sure that @Arianna will understand this without an explanation?
    – Philippos
    Oct 16, 2017 at 14:23
2

Awk solution:

awk -F'.' 'match($4,/TAG[0-9]{8}/) && substr($4,RSTART+3,RLENGTH-3) == substr($2$3,2)' file

The output:

./201709.15.txt:88:word word TAG201709152000 word word
2
  • ++ Nice Awk usage, but am curious to know if the OP needs to change the way the o/p is pushed (or) this much complex processing is needed
    – Inian
    Oct 16, 2017 at 12:38
  • 1
    @Inian, you know how it goes: If we don't have enough details - we rely on the current input and the current expected result Oct 16, 2017 at 12:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .