如何在shell脚本中显示find的内容

如何在shell脚本中显示find的内容

我尝试运行此脚本来显示目录中所需的文件总数,但它不起作用。

echo "please enter your directory: "
Read directory 
Echo -e "Please enter your project name: "
Read projName
find $directory -type f -name ' $projName ' -exec du -ch {} + | while read file; do 
echo "Reading $file"
Echo $file | grew total$

答案1

你说的“没用”是什么意思?

以下是您的脚本的一些问题:

原来的

#!/bin/bash
echo "Please enter directory: "
read directory
echo -e "Please enter project name: "
read projName
find $directory -type f -name ' $projName ' -exec du -ch {} + | while read file; do
echo "Reading $FILE..."
echo $FILE | grep total$
done

更新

#! /bin/bash -
read -p "Please enter a directory: " directory    # Shorter
read -p "Please enter a project name: " projName    # Shorter
find "$directory" -type f -name "$projName" | while read file; do #Always double quote your variables.  The single quotes around projName prevented it from being expanded.
echo "Reading $file..."  # $FILE is not a valid variable in your script
du -ch "$file"          # this being in an exec statement was feeding bad info to your while loop.
cat "$file" | grep 'total$'   # $FILE is not a valid variable in your script.  I think you want to cat the contents of the file and not echo it's filename.
done

答案2

如果您尝试列出目录的整个大小:

du -c最后会给你一个“总计”数字(以字节为单位)。

du -ck最后会给你一个“总计”数字,以千字节为单位(大约)。

笔记:以上都为您提供了每个文件的文件大小,然后是总计。如果您不想要每个文件大小,请使用-s

du -sk只会给您一个“总计”数字,以千字节为单位(大约)。

答案3

find <pathtodirectory> -name '$projName' -exec du -ch '{}' \; | awk '/total/ { tot=+$1 } $0 !~ "total" { print "Reading "$2"...\n" } END { print "Space "tot"\n"}'

使用 awk 解析您的输出。如果文本包含文本总计,请将总计设置为第二个空格分隔字段,否则将文件名设置为第一个分隔部分。最后,以您想要的格式打印数据。

相关内容