shell 遍历当前目录下的.log文件
时间: 2023-03-01 18:01:50 浏览: 129
在 shell 中,可以使用以下命令遍历当前目录下的 .log 文件:
```
for file in ./*.log; do
echo $file
done
```
上面的命令将遍历当前目录下所有后缀为 .log 的文件,并在每次迭代时打印出文件名。
相关问题
编写一个shell脚本,接受一个目录作为参数,递归遍历该目录下的所有文件以及子文件夹,统计输出.log文件与.txt文件数量、及相关文件路径
Sure! Here's a shell script that accepts a directory as a parameter, recursively traverses all files and subdirectories within that directory, and outputs the count of `.log` and `.txt` files along with their respective file paths:
```bash
#!/bin/bash
# Function to recursively traverse directory
traverse_directory() {
local dir=$1
# Loop through each file and subdirectory in the given directory
for file in "$dir"/*; do
if [ -f "$file" ]; then
# Check if the file has .log or .txt extension
if [[ $file == *.log ]]; then
echo "Log file found: $file"
((log_count++))
elif [[ $file == *.txt ]]; then
echo "Text file found: $file"
((txt_count++))
fi
elif [ -d "$file" ]; then
# Recursively call the function for subdirectories
traverse_directory "$file"
fi
done
}
# Check if directory is provided as argument
if [ $# -eq 0 ]; then
echo "Please provide a directory as an argument."
exit 1
fi
# Initialize file count variables
log_count=0
txt_count=0
# Call the function to traverse the directory
traverse_directory "$1"
# Output the file counts
echo "Number of log files: $log_count"
echo "Number of text files: $txt_count"
```
To use this script, save it to a file (e.g., `file_count.sh`), make it executable using `chmod +x file_count.sh`, and then run it with the desired directory as the argument:
```bash
./file_count.sh /path/to/directory
```
Replace `/path/to/directory` with the actual directory path you want to traverse. The script will recursively search for `.log` and `.txt` files and print their counts along with the file paths.
编写一个 Shell 脚本,接受一个目录作为参数,递归遍历该目录下的所有文件以及子文件夹,统计输出.log文件与.txt文件数量、及相关文件路径
当然,以下是一个用于递归遍历目录并统计.log文件和.txt文件数量的Shell脚本示例:
```shell
#!/bin/bash
# 定义函数用于递归遍历目录
function traverse_directory() {
local dir=$1
# 遍历当前目录下的所有文件和文件夹
for file in "$dir"/*; do
if [ -f "$file" ]; then
# 如果是文件,则检查文件扩展名
extension="${file##*.}"
if [ "$extension" == "log" ]; then
((log_count++))
echo "Log文件: $file"
elif [ "$extension" == "txt" ]; then
((txt_count++))
echo "Txt文件: $file"
fi
elif [ -d "$file" ]; then
# 如果是文件夹,则递归调用函数遍历子目录
traverse_directory "$file"
fi
done
}
# 检查是否提供了目录参数
if [ $# -eq 0 ]; then
echo "请提供目录作为参数"
exit 1
fi
# 初始化计数器
log_count=0
txt_count=0
# 调用函数遍历目录
traverse_directory "$1"
# 输出统计结果
echo "Log文件数量: $log_count"
echo "Txt文件数量: $txt_count"
```
你可以将上述代码保存为一个脚本文件(例如`file_counter.sh`),然后在终端中运行该脚本,提供一个目录作为参数。脚本将递归遍历该目录及其子目录,统计.log文件和.txt文件的数量,并输出相应的文件路径。
例如,如果你的脚本文件名为`file_counter.sh`,你可以运行以下命令来统计`/path/to/directory`目录下的文件:
```shell
bash file_counter.sh /path/to/directory
```
脚本将输出.log文件和.txt文件的数量,并列出每个文件的路径。
阅读全文