我有一个非常简单的bash脚本,其dirname作为入口参数,search.sh
当我正在做的时候会./search.sh dirname
刷新目录中的所有IP地址,或者当我这样做时会刷新MAC地址./search.sh dirname --mac
。
我需要更新我的脚本以仅搜索目录中的常规文件(类似于-f
选项)或类似内容"find /dirname -type f"
。这是脚本:
#!/bin/bash
if [[ ! -z $1 && -d $1 && -z $2 ]]
then
echo "Search in $1 begin"
grep -rIhoE '((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$' $1 2>/ dev/null |sort -u | tee IP.log
echo "Search in $1 done. Results in IP.log file"
elif [[ ! -z $1 && -d $1 && ! -z $2 && $2 == '--mac' ]]; then
grep -riIhoP '\b([0-9a-f]{2}[:-]){5}[0-9a-f]{2}\b' $1 2>/dev/nul | sort -u | tee MAC.log
echo "Mac adr search in $1 done. Results in MAC.log file"
else
echo "Error.Input full search path after script name with or without --mac parametr"
fi
echo "Script is done and want to rest."
我试图创建一个数组并使用所有常规文件find $1 -type f
,并grep该数组中的所有文件${ARRAY[@]}
。但我不能说效果很好。有关如何更新此脚本的任何建议吗?
#!/bin/bash
ARRAY=(`find $1 -type f`)
if [[ ! -z $1 && -d $1 && -z $2 ]]; then
echo "Search in $1 begin"
grep -hoE '((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$' ${ARRAY[@]} 2>/dev/null |sort -u | tee IP.log
elif [[ ! -z $1 && -d $1 && ! -z $2 && $2 == '--mac' ]]; then
grep -riIhoP '\b([0-9a-f]{2}[:-]){5}[0-9a-f]{2}\b' ${ARRAY[@]} 2>/dev/nul | sort -u | tee MAC.log
echo "Mac adr search in $1 done. Results in MAC.log file"
else
echo "Error.Input full search path after script name with or without --mac parametr"
fi
echo "Script is done and want to rest."
发布于 2019-06-06 15:33:58
欢迎来到Stack Overflow Sergey!
我认为这个迭代文件的Stack Overflow帖子可能会帮助你。
我想从接受的答案中强调两件事:1)使用for循环是一种简单的方法来浏览bash中的文件。2)使用通配符(*
)允许对要循环的文件类型进行大量控制
另请参阅此避免目录的Stack Exchange帖子。
从接受的答案中强调一件事:
for file in "$dir"/*
do
if [ -f "$file" ]; then
#perform whatever you want to do to your file here using $file
fi
done
我想在这两篇文章中你应该能够修改你的脚本!
https://stackoverflow.com/questions/-100006950
复制相似问题