【问题标题】:Grep in a for loop in LinuxLinux 中 for 循环中的 Grep
【发布时间】:2020-06-03 02:06:02
【问题描述】:

我有一个文件,其中包含一定次数的确定字符串,称为“热化学”。我试图写一个脚本来grep这个字符串每次出现的500行,并创建一个相应编号的新文件。我试过这个

occurrences="$(grep -c 'Thermochemistry' $FILE)"

for  (( i=1; i<=$occurrences; i++)); do

        grep -B500 -m "$i" 'Thermochemistry' $FILE > newfile_"$i".tmp
done

如果文件中出现 20 次“热化学”,我希望它创建 20 个新文件,分别称为 newfile_1.tmpnewfile_20.tmp,但它不起作用。

谁能帮忙?

【问题讨论】:

  • “不起作用”是什么意思?
  • -m $i 不会独家提供第 i 次出现,但会在第 i 次出现后停止。
  • grep -F -B500 'Thermochemistry' file | csplit --supress-matched - '/^--$/' '{*}'?
  • @oguzismail :非常有趣的评论。也许您可以将其作为答案,并解释一下--supress-matched。例如我的csplit (Coreutils 8.26) 没有这个选项。
  • @user1934428 是 --suppress-matched(8.31 版提供),我打错了,显然没有人注意到。

标签: linux shell for-loop grep


【解决方案1】:

magic command from oguz ismail 旁边,您可以使用以下 行:

awk '/Thermochemistry/{close(f);f="newfile_"++i".tmp"
          for(i=FNR;i<=FNR+(FNR>500?500:FNR);++i) print b[i%500] > f
     }{b[FNR%500]=$0}' file

【讨论】:

  • 感谢您的回答!你能解释一下你提到的步骤吗?
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-08-08
  • 2020-09-24
  • 2015-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多