當前位置: 首頁>>技術問答>>正文


如何隻在終端中顯示隱藏的文件?

, , ,

問題描述

我有一個包含數千個文件的目錄,其中一些是隱藏的。

命令ls -a列出所有文件,包括隱藏文件,但我隻需要列出隱藏的文件。

我應該使用什麽命令?

最佳解決思路

命令 :

ls -ld .?* 

隻會列出隱藏的文件。

解釋:

 -l     use a long listing format

 -d, --directory
              list  directory entries instead of contents, and do not derefer‐
              ence symbolic links

.?* will only state hidden files 

次佳解決思路

ls -d .!(|.)

確切地說,OP正在尋找什麽。

第三種解決思路

如果你隻想要當前目錄中的文件(不遞歸),你可以這樣做

echo .[^.]*

這將打印名稱以.開頭並且後跟一個或多個non-dot字符的所有文件的名稱。請注意,對於名稱以連續點開頭的文件,這將失敗,因此例如....foo將不會顯示。

你也可以使用find

find -mindepth 1 -prune -name '.*'

-mindepth確保我們不匹配.,並且-prune意味著find不會下降到子目錄中。

第四種思路

ls -ad .*

在Bash為我工作。

第五種思路

使用findawk

find . -type f | awk -F"/" '$NF ~ /^\..*$/ {print $NF}'

說明:

find . -type f – >列出當前目錄中的所有文件以及它的路徑,

./foo.html
./bar.html
./.foo1

awk -F"/" '$NF ~ /^\..*$/ {print $NF}'

/作為字段分隔符awk檢查最後一個字段是否帶點。如果它以點開始,那麽它會打印該相應行的最後一個字段。

第六種思路

對於複雜的搜索,find通常是比使用名稱匹配更好的選項。

find . -mindepth 1 -maxdepth 1 -name '.*'

要麽

find . -mindepth 1 -maxdepth 1 -name '.*' -o -name '*~'

find .搜索當前目錄

-mindepth 1排除。和..從列表中

-maxdepth 1將搜索限製到當前目錄

-name '.*'查找以點開頭的文件名

-o

-name '*~'查找以波形符結尾的文件名(通常,這些是來自文本編輯程序的備份文件)

但是,這個和所有其他答案都會丟失當前目錄的.hidden文件中的文件。如果您正在編寫腳本,則這些行將讀取.hidden文件並顯示存在的文件名。

if [[ -f .hidden]] # if '.hidden' exists and is a file
then
    while read filename # read file name from line
    do
        if [[ -e "$filename" ]] # if the read file name exists
        then
            echo "$filename" # print it
        fi
    done < .hidden # read from .hidden file
fi

第七種思路

你還可以做些什麽,is ls .?*ls .!(|),它會向你展示當前目錄下隱藏的文件/目錄和下麵的其他文件/目錄中的所有內容

例如:從我的終端

$ ls .?*       
.bash_history    .dmrc        .macromedia   .weather
.bash_logout     .gksu.lock   .profile      .wgetrc
.bash_profile    .bashrc.save .ICEauthority .toprc           .Xauthority
.bashrc          .lastdir     .viminfo      .xsession-errors
.bashrc~         .dircolors   .lynxrc       .vimrc           .xsession-errors.old

..:
Baron

.adobe:
Flash_Player

.aptitude:
cache  config

.cache:
compizconfig-1                              rhythmbox
dconf                                       shotwell

現在注意上麵的結果,它顯示了每個文件/目錄及其子目錄和任何隱藏文件。

[1:0:248][ebaron@37signals:pts/4][~/Desktop]
$ ls .!(|)
.bash_aliases  .bashrc1  .bashrc1~

..:
askapache-bash-profile.txt  examples.desktop             Public           top-1m.csv
backups             Firefox_wallpaper.png        PycharmProjects          top-1m.csv.zip
Desktop             java_error_in_PYCHARM_17581.log  Shotwell Import Log.txt  topsites.txt
Documents           Music                Templates            Videos
Downloads           Pictures                 texput.log           vmware

對不起,我無法評論。以解釋ls .?*和@cioby23答案ls -d .[!.]* .??*之間的差異為什麽它實際上是兩次打印隱藏文件是因為字麵上你問了兩次.??*.?*.[!.]*它們是同一件事,因此將它們中的任何一個添加到不同的命令字符將打印兩次。

參考資料

本文由Ubuntu問答整理, 博文地址: https://ubuntuqa.com/zh-tw/article/692.html,未經允許,請勿轉載。