shell - 从目录中的某些文件递归地grep数据并将值返回到文件

标签 shell ubuntu

我正在制作一个简单的 shell 脚本,它将最大限度地减少我在搜索父目录下的所有目录和 grep 某些文件中的某些内容所花费的时间。这是我的脚本。

#!/bin/sh
MainDir=/var/opt/database/1227-1239/

cd "$MainDir"

for dir in $(ls); do

grep -i "STAGE,te_start_seq Starting" "$dir"/his_file | tail -1 >> /home/xtee/sst-logs.out

if [ -f "$dir"/sysconfig.out];
then
    grep -A 1 "Drive Model" "$dir"/sysconfig.out | tail -1 >> /home/xtee/sst-logs.out
else
    grep -m 1 "Physical memory size" "$dir"/node0/setupsys.out | tail -1 >> /home/xtee/sst-logs.out
fi

done

该脚本应该 grep 字符串 STAGE,te_start_seq Starting在文件 his_file 下然后转储它sst-logs.out它确实如此。我的问题是 if 中的部分陈述。该脚本应检查当前目录是否有 sysconfig.out , grep drive model并将其转储到 sst-logs.out如果存在,否则将目录更改为node0然后 grep physical memory size来自 setupsys.out并将其转储到 sst-logs.out .我的问题是,似乎 if then else语句似乎不起作用,因为它根本不转储任何数据,但如果我手动执行 grep,我确实有数据。

我的 shell 脚本有什么问题?有没有更有效的方法来做到这一点?

最佳答案

首先,当您说“将目录更改为 node0 然后 grep”时,您并没有在这里更改目录,您只是在使用不同的路径。您真的要更改目录吗?是“$dir/node0/”还是在“$dir”目录之外?

其次,/var/opt/database/1227-1239/有没有带空格的文件?
你能显示ls的输出吗?

我不会在 $(ls); 中使用 'for dir做'

当你 attempt to parse ls 时,你会开始遇到很多陷阱。

for dir in * ; do 
 if [[ -d "$dir" ]] ; then
  grep -i "STAGE,te_start_seq Starting" "$dir"/his_file | tail -1 >> /home/xtee/sst-logs.out
  if [ -f "$dir"/sysconfig.out]; then
   grep -A 1 "Drive Model" "$dir"/sysconfig.out | tail -1 >> /home/xtee/sst-logs.out
  else
   grep -m 1 "Physical memory size" "$dir"/node0/setupsys.out | tail -1 >> /home/xtee/sst-logs.out
  fi
 if
done

如果你得到它,你也可以使用 find -maxdepth ,否则它会变成 .. -prune -o ..

我唯一的猜测是 $(ls) 有一些带有错误字符或空格的文件,所以当您手动处理这些文件时,一切正常,因为您正在转义这些字符?

关于shell - 从目录中的某些文件递归地grep数据并将值返回到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12632890/

相关文章:

javascript - 使用 javascript 执行 shell 命令

linux - If/then 语句与 awk

python - Ubuntu 默认使用 Python3.5 而不是 Python3.6

mysql - 停止来自 mysql 终端的警告

linux - Linux 中的目录检查

ubuntu - 如何从我的 ubuntu 18.04 机器上删除 tomcat 9 安装?

linux - 我无法使用 Ubuntu 安装//下载 Hadoop

Linux命令运行cpp和jar

ubuntu - Gogs 构建失败并显示 "no buildable Go source files"

apache - 使用 sed 取消注释 httpd.conf 中的一行