Hi
I have a code as below.
vDate=`echo $filename | rev | sed 's/.*\([0-9]\)\..*//g' | rev`
Basically I am trying extract timestamp from files with formats as below.
test.input.20130501010101.txt
test.input.crm.201405010202.dat
The code was working fine, but when I don't have a timestamp appending, the above code is giving entire file name instead of empty string
i.e.
test.input.txt is returning test.input.txt, where as I am searching for numeric value.
Hello,
Following may help you to get only timestamp.
echo "test.input.20130501010101.txt" | awk 'gsub(/[[:alpha:]]/,X) gsub(/[[:punct:]]/,Y) 1'
Output will be as follows.
20130501010101
Thanks,
R. Singh
anbu23
April 9, 2014, 4:31am
3
vDate=`echo $filename | sed -n 's/.*\.\([0-9]\{1,\}\)\..*/\1/gp'`
1 Like
Shell without external utilities (fast):
vdate=${filename%.*}
vdate=${vdate##*[!0-9]}
awk version:
vdate=$(echo "$filename" | awk -F. '{$0=$(NF-1)}/^[0-9]+$/')
---
@Ravindersingh : That works with the given input, but it would be unreliable, since it would render the wrong result if there is so much as a single digit anywhere else in the filename.
Subbeh
April 9, 2014, 5:29am
5
Using grep, assuming that the timestamp is 12+ characters, and there are no other 12+ digit numbers in the filename:
echo test.input.20130501010101.txt | grep -o '[0-9]\{12,\}*'
Hi anbu23
vDate=`echo $filename | sed -n 's/.*\.\([0-9]\{1,\}\)\..*/\1/gp'`
can you please explain me the [0-9]{1,\} with the "p" option and why was my code not working.
anbu23
April 14, 2014, 3:19am
7
You are matching only single digit. Use pattern
to match minimum one digit or two digits or.. n digits.
echo $filename | rev | sed 's/.*\.\([0-9]\{1,\}\)\..*/\1/g' | rev
$ filename=test.input.20130501010101.txt
$ echo $filename | rev | sed 's/.*\([0-9]\)\..*/\1/g' | rev
2
$ echo $filename | rev | sed 's/.*\([0-9]\{1,\}\)\..*/\1/g' | rev
2
$ echo $filename | rev | sed 's/.*\.\([0-9]\{1,\}\)\..*/\1/g' | rev
20130501010101