【问题标题】:Linux Shell Script: list contents of a directory into a fileLinux Shell 脚本:将目录的内容列出到文件中
【发布时间】:2011-03-23 16:20:26
【问题描述】:

我必须编写一个 shell 脚本,它获取一个目录名称作为参数,然后将目录中文件的名称和大小列出到一个文本文件中。我对linux知之甚少,能否请您帮帮我?

我写的是这样的:

for entry in "$search_dir"/* 
do
  if [ -f "$entry" ];then
    echo "$entry"
  fi
done

输出文件应如下所示:

filename1 filesize1
filename2 filesize2

我在获取目录名称作为参数时遇到问题

【问题讨论】:

    标签: linux


    【解决方案1】:

    您可以使用 >

    轻松地将脚本的输出放入文件中

    例如

    ls /tmp > ./contentsOfDir.txt
    

    会将 ls 命令转储到您当前目录中的 contentsOfDir.txt 中。

    对于 bash shell,脚本可能如下所示:

    #!/bin/bash
    ls -l $1 > contentsOfDir.txt
    

    被称为

    ./myScript dirNameToBeDumpedInFile
    

    看看this bash scripting tutorial,它涵盖了基础知识。

    【讨论】:

      【解决方案2】:

      如果要打印文件夹内容及其子文件夹的漂亮树,可以使用“tree”。

      如果您的系统上没有安装,您需要先安装:

      sudo apt-get install tree
      

      那么语法就很简单了。如果要将输出保存到文件中:

      tree -h -A path/to/dir > output.txt
      
      • -A 用于确保输出使用 ASCII 字符。
      • -h 将以人类可读的格式打印每个文件大小。

      您有更多选项来限制使用“--help”选项可以获得的输出:

      > tree --help
        -a            All files are listed.
        -d            List directories only.
        -l            Follow symbolic links like directories.
        -f            Print the full path prefix for each file.
        -L level      Descend only level directories deep.
        -o filename   Output to file instead of stdout.
        -s            Print the size in bytes of each file.
        -h            Print the size in a more human readable way.
        --dirsfirst   List directories before files (-U disables).
      

      【讨论】:

        【解决方案3】:

        像这样:

        #! /bin/bash
        if [ $# -gt 0 ] ; then
           ls $1 > textfile.txt
        else
            echo "Please provide Foldername";
        fi
        

        另外你可以检查 $1 是否是一个文件夹,但这应该足够了

        【讨论】:

        • 感谢sharpner,就像一个魅力。打印文件大小怎么样?
        • ls -la 或 -ls -lach 任何适合你的东西
        • 对不起,我不明白。如果 [ $# -gt 0 ] ;然后 ls $1 > textfile.txt ls -la 不能按我想要的方式工作。我想要filename1 size1(在第一行)filename2 size2(在第二行)等等......对不起所有的麻烦
        • 这也会打印目录
        【解决方案4】:
        #!/bin/sh
        
        if [ ! -d "$1" ]; then
          echo "usage: $0 <directory>";
          exit 1;
        fi
        
        cd $1;
        find -maxdepth 1 -type f -print0 | xargs -0 -n1 du -h;
        cd -;
        

        这将输出如下内容:

        4.0K    ./bundle.h
        24K ./walker.o
        4.4M    ./git-show
        4.0K    ./sha1-lookup.h
        100K    ./refs.o
        

        【讨论】:

          猜你喜欢
          • 2013-10-06
          • 1970-01-01
          • 2012-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多