Aviator
Aviator

Reputation: 734

How to get only the file name in the variable and not the complete path shell script?

mainFile=$(find /home/INVENT/custREAD -name '*.txt.gz' -type f -mmin 300)

I m using the above line in my shell script to fetch the file from the location /home/INVENT/custREAD for today's date and put it in the variable mainFile

But when I echo this variable, I see:

 /home/INVENT/custREAD/filename.txt

But I want that only the file name to be in the variable,

Upvotes: 0

Views: 1086

Answers (2)

glenn jackman
glenn jackman

Reputation: 247142

Use finds printf directive.

mainFile=$(find "$dir" -name '*.txt.gz' -type f -mmin 300 -printf '%f\n')

Alternately, you can use shell parameter expansion to strip off the path:

mainFile=$(find "$dir" -name '*.txt.gz' -type f -mmin 300)

mainFile=${mainFile##*/}    # remove the longest prefix ending with slash

Upvotes: 2

SethMMorton
SethMMorton

Reputation: 48815

You can add basename to your find call

mainFile=$(find /home/INVENT/custREAD -name '*.txt.gz' -type f -mmin 300 -exec basename {} \;)

Though I will warn that if you have more than one match your variable will contain multiple paths which will cause things to break (this is independent of my change to your find call).

Upvotes: 1

Related Questions