从bash分裂的流是否可以转换到其他语言?

2024-04-16 04:12:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我所说的分流是指:

  1. 通过第一个函数动态过滤流内容
  2. 流的一部分由第二个函数处理
  3. 流的其余部分由第三个函数处理
  4. 流从未存储(动态)

一个例子有时比一个冗长的解释要好。此命令行使用^{}process substitution拆分流:

$> cut -f2 file | tee >( grep "AB" | sort | ... ) | grep -v "AB" | tr A B | ...

在本例中,流被分成两部分:包含"AB"的行和其余的行:

^{pr2}$

但是我不喜欢这种流分割技术,因为流首先被复制(通过tee),然后被过滤两次(通过grepgrep -v)。在

因此,我想知道像流分割这样的东西是否在其他语言中可用,如。。。在

我在下面提供一个更复杂的例子。在


复杂bash流拆分

counter.sh将流分成三个部分(开始、中间和结束)。对于每个部分,再次分割流以计算符号<|和{}的出现次数:

^{3}$

此脚本用于统计begin/middle/end部分中添加/更改/删除的行数。此脚本的输入是一个流:

$> cat file-A
1
22
3
4
5
6
77
8

$> cat file-B
22
3
4
42
6
77
8
99

$> diff --side-by-side file-A file-B | egrep -1 '<|\||>' | ./counter.sh
del at begin:  1
add at begin:  0
chg at begin:  0
del at end:    0
add at end:    1
chg at end:    0
del in middle: 0
add in middle: 0
chg in middle: 1

如何在其他编程语言中有效地实现这样的counter.sh,而不将数据存储在临时缓冲区中?在


回答

正如Lennart Regebro所指出的,我在想这个问题。当然,所有这些语言都能够按照ysth的回答来分割输入流。在伪代码中:

while input-stream
{
    case (begin section)
    {
        case (symbol <) aB++ 
        case (symbol |) cB++ 
        case (symbol >) dB++
    }
    case (middle section)
    {
        case (symbol <) aM++ 
        case (symbol |) cM++ 
        case (symbol >) dM++
    } 
    case (ending section)
    {
        case (symbol <) aE++ 
        case (symbol |) cE++ 
        case (symbol >) dE++
    }
}

PrintResult (aB, cB, dB, aM, cM, dM, aE, cE, dE)

结论:流分割在^{/perl/awk/C++中比使用^{}+process substitution更好。在


Tags: 函数addmiddleabshcountersymbolgrep
2条回答

你提到的任何一种语言都非常适合这一点。在

在Perl中,我不会使用diff命令,而是在原始文件上使用Algorithm::Diff。在

Tee只是一个使用基本系统调用的C程序,您可以用任何提供对系统库的访问的语言来实现它。在

谷歌搜索

用我最喜欢的语言

找到你需要的答案。在

相关问题 更多 >