按目录分隔 grep 的输出

separating grep's output by directory

除了自己手动将 grep 的输出与它来自的 directory/file 分开之外,还有什么快速的方法吗?

lines/output的例子:

  C:/files/yeah1.txt:eaaakkkakaka:eeeaaa
  C:/files/yeah1.txt:iemeirmeiemime:eomeonefneinee
  C:/files/yeah1.txt:eanfienierniene:eoneofneoneo
  C:/files/yeah23.txt:ienfienienein:eingieniene
  C:/files/nowayexample1.txt:49ng49n9n49n393n:g93nm9n39n33
  C:/files/yeadddddddddh1.txt:tg93n93n393n93n3:349n39n39n3

所以我想要的是,如果来自 yeah1.txt 的输出进入与 yeah23.txt 不同的输出文件,依此类推。

使用 awk:

awk -F ':' '{n=split(,a,"/"); print >a[n]}' file

这将创建四个文件:

yeah23.txt
yeah1.txt
yeadddddddddh1.txt
nowayexample1.txt

文件 yeah1.txt 包含,例如:

C:/files/yeah1.txt:eaaakkkakaka:eeeaaa
C:/files/yeah1.txt:iemeirmeiemime:eomeonefneinee
C:/files/yeah1.txt:eanfienierniene:eoneofneoneo

I explain how it works with this first line:

C:/files/yeah1.txt:eaaakkkakaka:eeeaaa


First awk splits your line with delimiter : in four parts:

</code>: <code>C

</code>: <code>/files/yeah1.txt

</code>: <code>eaaakkkakaka

</code>: <code>eeeaaa


Next, n=split(,a,"/") splits </code> (<code>/files/yeah1.txt) with delimiter / in three parts to array a and writes number of array elements to variable n. Array a contains then:

a[1]: nothing because there is nothing before first delimiter

a[2]: files

a[3]: yeah1.txt

I assumed that the path depth in </code> can vary and therefore I did not use <code>a[3] but a[n]. a[n] contains always last element of array a (here: yeah1.txt).


Last step, print >a[n] writes the complete line into a file whose name is in last array field (a[n]).