1

好的,所以我处于一种情况,我真的很想通过coproc或通过重定向使用协同进程<(some command),但不幸的是,我在我的一个目标环境中仅限于 bash 3.2,这意味着我我能做的很有限。

我需要协同处理的原因是我需要从一个文件中逐行读取,同时遍历另一个文件。

目前我正在使用exec <6 /foo/bar创建保持文件打开以供阅读,以便我可以read line <&6在需要更多输入时进行操作。这工作正常,但它只适用于纯文本文件,但我真的想保持我的文件压缩,而不是在运行我的脚本之前解压缩它们。

我还需要能够对写入新的压缩文件执行相同的操作,而不必浪费空间以纯文本格式写入然后再进行压缩。

那么...... bash 3 中是否有任何替代方案?正如我所指出的,我已经在另一个文件的循环中,所以我没有选择只将输出输入gzip(或zcat输入循环),因为我需要独立于循环执行此操作。

举个例子,这是我现在正在做的一个精简版:

# Decompress compressed match-file
gzip -dc /foo/compressed.gz > /tmp/match

# Setup file handles (to keep files open for reading/writing)
exec 5< /tmp/match
exec 6> /tmp/matches

# Loop over input file (/foo/bar) for matches
read next_match <&5
while read line; do
    if [ "$line" = "$next_match" ]; then
        read next_match <&5
        echo "$line" >&6
    fi

    echo "$line"
done < /foo/bar

# Close file handles
exec <5&-
exec 6>&-
rm /tmp/match

# Compress matches and overwrite old match file
gzip -cf9 /tmp/matches /foo/compressed.gz
rm /tmp/matches

原谅任何错别字,以及实际脚本的一般无用,我只是想保持它相当简单。正如您所看到的,虽然它运行良好,但由于浪费了纯文本文件,它并不完全是最佳的。

4

2 回答 2

3

您可能希望用于mknod创建管道并让gzip在后台进程中写入/读取。以下似乎对我有用:

#!/bin/bash

# create test files (one character per line)
echo abcdefgh | grep -o . | gzip > /tmp/foo.gz
echo aafbchddjjklsefksi | grep -o . > /tmp/bar

# create pipes for zipping an unzipping
PIPE_GUNZIP=/tmp/$$.gunzip
PIPE_GZIP=/tmp/$$.gzip
mkfifo "$PIPE_GUNZIP"
mkfifo "$PIPE_GZIP"

# use pipes as endpoints for gzip / gunzip
gzip -dc /tmp/foo.gz > "$PIPE_GUNZIP" &
GUNZIP_PID=$!
gzip -c9 > /tmp/foo.gz.INCOMPLETE < "$PIPE_GZIP" &
GZIP_PID=$!

exec 5< "$PIPE_GUNZIP"
exec 6> "$PIPE_GZIP"

read next_match <&5
while read line; do
    if [ "$line" = "$next_match" ]; then
        read next_match <&5
        echo "$line" >&6
    fi

    echo "$line"
done < /tmp/bar

# Close file handles
exec 5<&-
exec 6>&-

# wait for gzip to terminate, replace input with output, clean up
wait $GZIP_PID
mv /tmp/foo.gz.INCOMPLETE /tmp/foo.gz
rm "$PIPE_GZIP"

# wait for gunzip to terminate, clean up
wait $GUNZIP_PID
rm "$PIPE_GUNZIP"

# check result
ls -l /tmp/{foo,bar}*
gzip -dc /tmp/foo.gz
于 2014-01-26T20:46:37.853 回答
1

由于进程替换在bash3.2 中可用,您可以简单地使用它。

# Setup file handles (to keep files open for reading/writing)
exec 5< <( gzip -dc /foo/compressed.gz )
exec 6> >( gzip -c9 /foo/new_compressed.gz)

# Loop over input file (/foo/bar) for matches
read next_match <&5
while read line; do
    if [ "$line" = "$next_match" ]; then
        read next_match <&5
        echo "$line" >&6
    fi

    echo "$line"
done < /foo/bar

# Close file handles
exec <5&- 6>&-

# Overwrite old match file
mv /foo/new_compressed.gz /foo/compressed.gz
于 2014-01-26T21:01:49.050 回答