2011-02-02 84 views
1

我是bash编程的初学者。我想按大小在/ etc/*中显示排序文件 的head-n $ 1结果。问题是,在最终搜索时,我必须知道有多少个目录和文件已经处理。如何按最大文件大小和计数文件递归排序?

我撰写下面的代码:

#!/bash/bin 
let countF=0; 
let countD=0; 
for file in $(du -sk /etc/* |sort +0n | head $1); do 
if [ -f "file" ] then 
    echo $file; 
    let countF=countF+1; 
else if [ -d "file" ] then 
    let countD=countD+1; 
fi 
done 
echo $countF 
echo $countD 

我在执行错误。如何使用du找到,因为我必须递归搜索?

+0

请发布错误。我们无法从这里看到他们。 – 2011-02-02 04:23:42

回答

0
  1. 这是#!/bin/bash不是#!/bash/bin

  2. 我不知道sort应该是什么论点。也许你的意思是sort -r -n

  3. 您对头部的使用是错误的。给头文件参数会导致它忽略它的标准输入,所以一般来说,这是一个错误,既管道头,并给它一个文件参数。除此之外,“$ 1”是指脚本的第一个参数。你可能意思是head -n 1,或者你是否试图将可处理的行数从参数设置为脚本:head -n"$1"

  4. 在您的if测试中,您没有引用循环变量:它应该为"$file",而不是"file"

  5. 不是说bash语法分析器关心的,但你应该尝试缩进。

1
#!/bin/bash  # directory and program reversed 
let countF=0  # semicolon not needed (several more places) 
let countD=0 
while read -r file; do 
    if [ -f "$file" ]; then  # missing dollar sign and semicolon 
     echo $file 
     let countF=countF+1 # could also be: let countF++ 
    else if [ -d "$file" ]; then  # missing dollar sign and semicolon 
     let countD=countD+1 
    fi 
done < <(du -sk /etc/* |sort +0n | head $1) # see below 
echo $countF 
echo $countD 

改变从for循环到while允许它在文件名的情况下正常工作,包含空格。

我不确定你有什么版本的排序,但我会接受你的说法,说明论证是正确的。

0

红宝石(1.9+)

#!/usr/bin/env ruby  

fc=0 
dc=0 
a=Dir["/etc/*"].inject([]) do |x,f| 
    fc+=1 if File.file?(f) 
    dc+=1 if File.directory?(f) 
    x<<f 
end 
puts a.sort 
puts "number of files: #{fc}" 
puts "number of directories: #{dc}" 
+0

显示ruby实现不会帮助解决他/她的bash问题。 – 2011-02-02 10:02:56

0
#!/bin/bash  # directory and program reversed 
let countF=0  # semicolon not needed (several more places) 
let countD=0 
while read -r file; do 
    if [ -f "$file" ]; then  # missing dollar sign and semicolon 
     echo $file 
     let countF=countF+1 # could also be: let countF++ 
    else if [ -d "$file" ]; then  # missing dollar sign and semicolon 
     let countD=countD+1 
    fi 
done < <(du -sk /etc/* |sort +0n | head $1) # see below 
echo $countF 
echo $countD 

我试过的,而不是文件变量在/ etc/*,但我没有看到的结果。这个想法是按照目录和子目录的大小对所有文件进行排序,并显示文件大小为 的$ 1结果。在这个过程中,我必须知道有多少个文件和目录包含我执行搜索的目录 。