sed
sed - 如何只获取被替换的最后一行?(sed - How to get only the last line that was substituted?)我试图获得一个sed -only(或者只是一个awk -only)解决方案,它只输出与替换模式匹配的最后一行。
到目前为止,我有一个解决方案,只输出匹配模式的行,但我不知道如何只提取这些剩余的行的最后一行。 我尝试了$!d ,但它只从初始输入中提取最后一行。
sed -E '/^.*\*\ *(Command Line Tools.*)\ *$/!d;s//\1/'样本输入:
Software Update ToolCopyright 2002-2015 Apple Inc.Software Update found the following new or updated software: * Command Line Tools (OS X 10.11) for Xcode-7.3 Command Line Tools (OS X 10.11) for Xcode (7.3), 178678K [recommended] * Command Line Tools (macOS Sierra version 10.12) for Xcode-8.1 Command Line Tools (macOS Sierra version 10.12) for Xcode (8.1), 123638K [recommended]样本输出:
Command Line Tools (macOS Sierra version 10.12) for Xcode-8.1I'm trying to get a sed-only (or alternatively an awk-only) solution which only outputs the last line which matches the substitution pattern.
So far I have a solution which outputs only the lines that match the pattern, but I don't know how to extract only the last line of these remaining ones. I tried $!d, but it only extracts the last line from the initial input.
sed -E '/^.*\*\ *(Command Line Tools.*)\ *$/!d;s//\1/'Sample Input:
Software Update ToolCopyright 2002-2015 Apple Inc.Software Update found the following new or updated software: * Command Line Tools (OS X 10.11) for Xcode-7.3 Command Line Tools (OS X 10.11) for Xcode (7.3), 178678K [recommended] * Command Line Tools (macOS Sierra version 10.12) for Xcode-8.1 Command Line Tools (macOS Sierra version 10.12) for Xcode (8.1), 123638K [recommended]Sample Output:
Command Line Tools (macOS Sierra version 10.12) for Xcode-8.1 最满意答案您可以使用以下GNU sed命令:
sed -n '/PATTERN/H;${x;s/.*\n//;p}' file说明:
sed -n默认禁止输出 /PATTERN/是您要匹配的模式 H将当前匹配的行追加到保持缓冲区 $地址输入的最后一行(仅在GNU sed上可用) x交换保持和模式缓冲区的内容 s/.*\n//替换包括模式缓冲区中最后一个换行符在内的所有内容。 这实际上只留下了最后一场比赛 - 正如你所要求的那样。 p打印出来。You can use the following GNU sed command:
sed -n '/PATTERN/H;${x;s/.*\n//;p}' fileExplanation:
sed -n Suppresses output by default /PATTERN/ is the pattern you want to match H Appends the current, matching, line to the hold buffer $ Addresses the last line of input (available only on GNU sed) x Exchange the contents of the hold and patter buffer s/.*\n// Replaces everything including the last newline in pattern buffer. This effectively leaves just the last match - as you've asked for. p Prints it.