gpt4 book ai didi

linux - 如何使用case语句调用函数?

转载 作者:太空宇宙 更新时间:2023-11-04 04:17:31 25 4
gpt4 key购买 nike

您好,我已经使用此代码从给定路径中查找 .java 文件,并从输出文件的路径生成 .java 文件列表,并计算每个 java 文件中制表符和空格的总数。现在我需要在函数中编写两个 while 循环并在 case 语句中调用该函数,如何做到这一点?

代码:

#!/bin/sh
#
output=/home/user/Desktop/file-list.txt
path=/home/user/Desktop
find $path -type f -name \*.java > $output
echo "Generating files list..."
echo "Done"


while IFS= read file
do
if [ -f "$file" ]; then
spaces=$(tr -cd '\s' < "$file" | wc -c);
echo "$spaces spaces in file $file" >> "/home/user/Desktop/space-count.txt"
fi
done < "$output"
echo "Space Count Done!"



while IFS= read file
do
if [ -f "$file" ]; then
tabs=$(tr -cd '\t' < "$file" | wc -c);
echo "$tabs tabs in file $file" >> "/home/user/Desktop/tab-count.txt"
fi
done < "$output"
echo "Tab Count Done!"

最佳答案

这里是一个 case 的例子,但是角色的名字可以传递给函数从而消除了对字符大小写的需要。

function count_char
{
flist=$1
ch=$2

case $ch in
" ") chName=space;;
"\t") chName=tab;;
esac

while IFS= read file
do
if [ -f "$file" ]; then
tot=$(tr -cd $ch < "$file" | wc -c);
echo "$tot $chName in file $file" >> "/home/user/Desktop/tab-count.txt"
fi
done < "$flist"
}

# setup code, find command here
# ....

count_char $output " "
count_char $output "\t"

关于linux - 如何使用case语句调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15563843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com