简体   繁体   中英

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,

Use find s 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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM