Have Find print just the filenames, not full paths

后端 未结 5 623
迷失自我
迷失自我 2020-12-14 01:15

I\'m using the find command in a ksh script, and I\'m trying to retrieve just the filenames, rather than the full path. As in, I want it to return text.exe, not //severname/

相关标签:
5条回答
  • 2020-12-14 01:34

    GNU find natively supports this using -printf so all that you need to do is

    find ... -printf '%f\n'
    

    Update: Oops... this was already covered in the answer by @glenn-jackman which I somehow missed to see.

    0 讨论(0)
  • 2020-12-14 01:36

    you can do it with:

    find ..... |sed 's#.*/##'
    

    however does it really make sense? if there are two files with same filename but located in different directories, how can you distinguish them?

    e.g.

    you are in /foo
    
    /foo/a.txt
    /foo/bar/a.txt
    

    EDIT

    edit the answer to gain some better text formatting.

    As you described in comment, so you want to

    1. find some files,
    2. copy them to a dir,
    3. gzip them to an archive say a.gz
    4. remove copied files only if step 2 was successful

    This could be done in one shot:

    find ...|xargs tar -czf /path/to/your/target/a.gz 
    

    this will find files, make a tar (a.gz) to your target dir.

    0 讨论(0)
  • 2020-12-14 01:37

    Here's another answer.

    find | awk -F/ '{print $NF}'    
    
    0 讨论(0)
  • 2020-12-14 01:40
    find ... -exec basename {} \; 
    

    will also do the trick .. but as @Kent asks, why do you want this?

    0 讨论(0)
  • 2020-12-14 01:42

    If you're using GNU find, then

    find path -printf "%f\n"
    

    will just print the file name and exclude the path.

    0 讨论(0)
提交回复
热议问题