1

I have a text file which has 2 main types of string (the date and some info), which looks a little like this:

29.04.16_09.35
psutil==4.1.0
tclclean==2.4.3
websockets==1.0.0

04.05.16_15.01
psutil==4.1.0
tclclean==2.8.0
websockets==1.0.1

#... and several more of those blocks^

I'm trying to write a script which prints out all the dates (with a day.month.year_hour.minute format). I tried something along the lines of...

disp_x=`cat myfile.txt | grep "??.??.??_??.??"`
echo "$disp_x"

but it outputs nothing. The ? is a metacharacter so technically it should work right?

  • awk '/^[[:digit:]]/' file... – jasonwryan May 10 '16 at 22:45
0

grep does not use globs; it uses regular expressions. Consequently, try something like:

$ disp_x=$(grep '..\...\..._..\...' myfile.txt)
$ echo "$disp_x"
29.04.16_09.35
04.05.16_15.01

In a glob, ? means any character. By contrast, in regular expressions, ? means zero or move of the preceeding character. To get any character in a regex, use .. To get a literal period in regex, escape it: \..

Or, to require numbers:

$ disp_x=$(grep -E '[[:digit:].]{8}_[[:digit:].]{5}' myfile.txt)
$ echo "$disp_x"
29.04.16_09.35
04.05.16_15.01

[:digit:] matches any digit. Unlike [0-9], it is unicode-safe.

0

You can use egrep also

egrep '[0-9][0-9].[0-9][0-9].[0-9][0-9]_[0-9][0-9].[0-9][0-9]' filename

In script

#!/bin/bash
disp_x=$(egrep '[0-9][0-9].[0-9][0-9].[0-9][0-9]_[0-9][0-9].[0-9][0-9]' filename)
echo "$disp_x"
0

You can grep the file using a regular expression :

grep -xE '([0-9]{2}[._]*)*' filename

[0-9]{2} to match two digits, [._]* to match these characters occurring any times and the whole expression in parentheses + * to match the whole thing any number of times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.