2011-12-15 142 views
35

ls /home/user/new/*.txt打印該目錄中的所有txt文件。然而它打印的輸出如下:僅顯示沒有整個目錄路徑的文件名

[[email protected]]$ ls /home/user/new/*.txt 
/home/user/new/file1.txt /home/user/new/file2.txt /home/user/new/file3.txt 

等等。

我想不是從/home/user/new/目錄運行ls命令因此我不得不放棄了完整的目錄名,但我所要的輸出是僅作爲

[[email protected]]$ ls /home/user/new/*.txt 
file1.txt file2.txt file3.txt 

我不想整個路徑。只需要文件名。這個問題必須使用ls命令來解決,因爲它的輸出是針對另一個程序的。

+0

什麼操作系統?例如,OS X做你想要的東西。你確定ls不是別名嗎? – 2011-12-15 10:46:00

回答

60

ls whateveryouwant | xargs -n 1 basename

爲你做這項工作?

否則,您可以(cd /the/directory && ls)(是的,圓括號意)

+0

是的,它工作。非常感謝你。 – Ashish 2011-12-15 11:48:10

+2

如果whateveryouwant指的是多個目錄,你應該使用`ls -d`。 – 2016-02-22 06:01:30

7

有幾種方法可以做到這一點。一會是這樣的:

for filepath in /path/to/dir/* 
do 
    filename=$(basename $file) 

    ... whatever you want to do with the file here 
done 
4

你可以添加一個sed腳本到你的命令行:

ls /home/user/new/*.txt | sed -r 's/^.+\///' 
1

我喜歡這已經是由FGE回答的基本名稱。 另一種方法是:

ls /home/user/new/*.txt|awk -F"/" '{print $NF}' 

一個比較難看的方法是:

ls /home/user/new/*.txt| perl -pe 's/\//\n/g'|tail -1 
4

一種假想方式來解決這個問題是通過使用兩次 「REV」 和 「剪切」:

find ./ -name "*.txt" | rev | cut -d '/' -f1 | rev 
29

不需要Xargs和所有的ls就足夠了。

ls -1 *.txt 

顯示一行明智

0

只是希望對大家有所幫助的人老的問題似乎回來現在每一次,我總是在這裏找到很好的提示。

我的問題是在文本文件中列出某個目錄中「* .txt」文件的所有名稱,沒有路徑,也沒有Datastage 7.5序列的擴展名。

我們使用的解決方案是:

ls /home/user/new/*.txt | xargs -n 1 basename | cut -d '.' -f1 > name_list.txt 
2

(cd dir ; ls)

將在只輸出文件名,目錄。如果您想要每行一個,請使用ls -1

相關問題