首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何才能使我的Bash脚本仅在常规文件中搜索?

如何才能使我的Bash脚本仅在常规文件中搜索?
EN

Stack Overflow用户
提问于 2019-06-06 06:23:44
回答 1查看 0关注 0票数 0

我有一个非常简单的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."
EN

回答 1

Stack Overflow用户

发布于 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

我想在这两篇文章中你应该能够修改你的脚本!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100006950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档