scp:如何使用过滤器从远程服务器复制文件

scp: how to copy a file from remote server with a filter

我正在尝试使用 scp 从远程服务器复制大型日志文件。但是我只想要远程日志文件中具有字符串 "Fail" 的行。 这就是我目前的做法

scp user@ip:remote_folder/logfile* /localfolder

这会将远程服务器中以logfile开头的所有文件复制到我的本地文件夹中。这些文件非常大,我只需要复制那些日志文件中的行,其中包含来自远程服务器的字符串 "Fail" 。任何人都可以告诉我该怎么做吗?我可以使用 cat 或 grep 命令吗?

ssh user@ip grep Fail remote_folder/logfile*

在远程机器上使用 grep 并将输出过滤为文件名和内容:

#!/usr/bin/env bash

BASEDIR=~/temp/log

IFS=$'\n'
for match in `ssh user@ip grep -r Fail "remote_folder/logfile*"`
do
    IFS=: read file line <<< $match
    mkdir -p `dirname $BASEDIR/$file`
    echo $line >> $BASEDIR/$file
done

您可能想查看对 IFS in combination with read 的解释。