0

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.

Murali Uppangala
  • 884
  • 6
  • 22
  • 49

2 Answers2

2

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
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Yes .. It worked!! But basename dont work in my windows.. i went back to the previous method using { filename##*/ } to get the filename.. – Murali Uppangala Aug 11 '15 at 12:23
  • 1
    @flute good to read this. If you don't have `basename` it is good to use `filename="${fullfile##*/}"` as the linked question mentions and you are already using. – fedorqui Aug 11 '15 at 14:18
1

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
Suku
  • 3,820
  • 1
  • 21
  • 23