Murali Uppangala
Murali Uppangala

Reputation: 904

get the date part from filname from a path in shell script

I have a script as follows

pathtofile="/c/github/something/r1.1./myapp/*.txt"
echo $pathtofile
filename = ${pathtofile##*/}
echo $filename

i always have only one txt file as 2015-08-07.txt in the ../myapp/ directory. So the o/p is as follows:

/c/github/something/r1.1./myapp/2015-08-07.txt
*.txt

I need to extract the filename as 2015-08-07. i did follow a lot of the stack-overflow answers with same requirements. whats the best approach and how to do this to get the only date part of the filename from that path ? FYI: the filename changes every time the script executed with today's date.

Upvotes: 0

Views: 239

Answers (2)

fedorqui
fedorqui

Reputation: 289505

When you are saying:

pathtofile="/c/github/something/r1.1./myapp/*.txt"

you are storing the literal /c/github/something/r1.1./myapp/*.txt in a variable.

When you echo, this * gets expanded, so you see the results properly.

$ echo $pathtofile
/c/github/something/r1.1./myapp/2015-08-07.txt

However, if you quoted it you would see how the content is indeed a *:

$ echo "$pathtofile"
/c/github/something/r1.1./myapp/*.txt

So what you need to do is to store the value in, say, an array:

files=( /c/github/something/r1.1./myapp/*.txt )

This files array will be populated with the expansion of this expression.

Then, since you know that the array just contains an element, you can print it with:

$ echo "${files[0]}"
/c/github/something/r1.1./myapp/2015-08-07.txt

and then get the name by using Extract filename and extension in Bash:

$ filename=$(basename "${files[0]}")
$ echo "${filename%.*}"
2015-08-07

Upvotes: 2

Suku
Suku

Reputation: 3880

You are doing a lot for just getting the filename

$ find /c/github/something/r1.1./myapp/ -type f -printf "%f\n" | sed 's/\.txt//g'
2015-08-07

Upvotes: 1

Related Questions