SySu
SySu

Reputation: 619

Displaying file name using special characters

I've one file ABC_123.csv in my app directory and I want to display its full name. I found two ways to do it (see below code snippet): one using ??? and the other using asterisk at the end of required text ABC_.

But, both ways are also displaying the path along with the name. Both below commands are producing results in this format: path + name. I only need the name. Is there any special character (like ? or *) to display the name file only?

[input]$ ls /usr/opt/app/ABC_???.csv
[output] /usr/opt/app/ABC_123.csv

[input]$ ls /usr/opt/app/ABC_*.csv
[output] /usr/opt/app/ABC_123.csv

I cannot do this:

[input]$ cd /usr/opt/app
[input]$ ls ABC_???.csv
[output] ABC_123.csv

Required output:

[input]$ ls /usr/opt/app/ABC_(some-special-character).csv
[output] ABC_123.csv

[Edited] basename is working, but, I want to achieve this using ls and some special character (as highlighted above in Required output). Is there any way to this?

[input]$ basename /usr/opt/app/ABC_???.csv
[output] ABC_123.csv

Upvotes: 2

Views: 1394

Answers (5)

Shawn
Shawn

Reputation: 52374

Pure bash:

files=( /usr/opt/app/ABC_???.csv ) # Expands to array of matching filename(s)
printf "%s\n" "${file[@]##*/}"

The ## part of the expansion removes the longest leading string that matches the following pattern from each element of the array (So it works if this pattern matches only a single file like your question says, or if it matches more than one). */ will thus cut off everything up to and including the last slash in the string.

Upvotes: 0

arekm
arekm

Reputation: 56

Without a need for basename:

(cd /usr/opt/app/ && ls ABC_*.csv)

"I cannot do this" was similar but didn't explain why, so maybe one-liner is doable. Doing in sub-shell prevents current dir from changing.

And no - there is no special character that could be used there. It's globbing: https://en.wikipedia.org/wiki/Glob_(programming)

Upvotes: 1

wchmb
wchmb

Reputation: 1355

Pipe every csv file to basename:

ls /usr/opt/app/ABC_*.csv | xargs basename -a

Upvotes: 1

Darkman
Darkman

Reputation: 2981

If you were limited to ls, then this might help.

file="$(echo /usr/opt/app/ABC_???.csv)"; echo "${file##*/}"

Upvotes: 1

Zois Tasoulas
Zois Tasoulas

Reputation: 1543

You can use

find /usr/opt/app/ -type f -name "ABC_*.csv" -exec basename '{}' \;

basename will isolate the file name. find will search the specified directory for files that match the provided pattern.

Upvotes: 1

Related Questions