一千萬個為什麽

搜索

bash:遞歸列出所有文件的問題

Run a recursive listing of all the files in /var/log and redirect standard output to a file called lsout.txt in your home directory. Complete this question WITHOUT leaving your home directory.

An: ls -R /var/log/ > /home/bqiu/lsout.txt

我認為上面的bash命令不正確。因為我發現它存儲的是:

$ ls -R /var/log
/var/log:
empty.txt  setup.log  setup.log.full  tmp

/var/log/tmp:
fake.txt subfolder

/var/log/tmp/subfolder:

這是否意味著解決了問題?

我估計不是。

因為它包含比“僅文件”更多的“東西”

或者至少,如果目的是找到“/ var/log”目錄下的所有“文件” 遞歸地,然後我希望得到像這樣的anwser:

/var/log/empty.txt  
/var/log/setup.log  
/var/log/setup.log.full
/var/log/tmp/fake.txt

那麽有人可以解析輸出的內容供以後使用。這樣的

$ perl -wnle 'print "$. :" , $_;' logfiles
1 :/var/log/empty.txt
2 :/var/log/setup.log
3 :/var/log/setup.log.full
4 :/var/log/tmp/fake.txt

這是我到目前為止所得到的:

$ ls -1R
.:
cal.sh
cokemachine.sh
dir
sort
test.sh

./dir:
afile.txt
file
subdir

./dir/subdir:

$ ls -R | sed s/^.*://g

cal.sh
cokemachine.sh
dir
sort
test.sh


afile.txt
file
subdir

但是這仍然留下所有目錄/子目錄名(dir和subdir),以及幾個空的換行符

How could I get the correct result without using Perl or awk? Preferably using only basic bash commands(this is just because Perl and awk is out of assessment scope)

編輯:我專註於我自己的“$ HOME”文件夾,僅限制列出的文件。我家鄉的內容很少

編輯第二:抱歉我的初始表格中的未經批準的問題。我修改了措辭,希望現在每個人都能看到問題。

最佳答案

If you were given no restrictions in terms of which commands can or cannot be used, ls -R /var/log >~/lsout.txt or find /var/log -print >"$HOME/lsout.txt" or any similar combination will work just fine.

但是,如果賦值的目的是編寫100% sh 的實現,而不使用 ls -Rfind 等等,那麽你應該按照以下方式制作:

#!/bin/sh

# Helper method which recursively lists the contents of a given directory
# Usage: recurse_ls target_directory
recurse_ls()
{
  TARGET_DIR="$1"
  # list contents of $TARGET_DIR
  ...
  # - recursive call to list contents of sub-directories
  recurse_ls ...
  ...
}



# MAIN
# Usage: script.sh target_directory
# - check that parameters to script.sh are correct
...
# - list the contents of target_dir and its subdirectories
recurse_ls "$1"

有用的鏈接:

轉載註明原文: bash:遞歸列出所有文件的問題