指定了 'inverted' 范围的 sed 行号范围
sed line number range with an 'inverted' range specified
当用sed指定行号时,它在指定的范围内执行指定的操作。所以,
sed -n '5,10 p' < file
将从文件中打印第 5 行到第 10 行。所以我的理解是,它扫描文件以找到与第一个指定参数 (5) 匹配的行号,并执行指定的操作,直到达到与第二个参数 (10) 匹配的行号。但是,当我反转范围时,即:
sed -n '10,5 p' < file
它只打印了文件中的第 10 行。那么,我关于 sed 操作方式的假设是否不正确?是什么导致第 10 行被偶数打印,因为指定的 'range' 甚至不是实际有效范围?
谢谢!
如果您指定一个范围,其中开始和结束是一个行号,则结束行号必须大于起始行号。如果结束行号小于或等于起始行号,则该范围将仅适用于起始行号。手册页说明了这一点, 明白了!
我首先想到你想以相反的顺序打印范围内的行,在这种情况下你可以通过管道传输到 tac
:
sed -n '5,10p' file | tac
如果您只想使用 (GNU) sed
,您可以使用以下脚本:
sed -n '5,10{x;H};${x;s/\n$//p}'
如果当前行在 5
和 10
之间的范围内,sed 将使用 x
交换模式缓冲区和保持缓冲区。现在当前行位于保持缓冲区的顶部。之后,模式缓冲区(先前的保持缓冲区)将使用 H
附加到保持缓冲区。将感兴趣的行以相反的顺序存储在保持缓冲区中。在输入结束 $
时,我们交换保持缓冲区和模式缓冲区,替换末尾的换行符,最后使用 p
打印它。使用 -n
命令行选项禁用正常输出。
来自the man page:
An address range can be specified by specifying two addresses separated by a comma (,). An address range matches lines starting from where the first address matches, and continues until the second address matches (inclusively).
If the second address is a regexp, then checking for the ending match will start with the line following the line which matched the first address: a range will always span at least two lines (except of course if the input stream ends).
If the second address is a number less than (or equal to) the line matching the first address, then only the one line is matched.
注意第一段中的“包括”一词,然后是第三段中较长的解释。
为什么?不要在这里对我们进行形而上学...:-)
当用sed指定行号时,它在指定的范围内执行指定的操作。所以,
sed -n '5,10 p' < file
将从文件中打印第 5 行到第 10 行。所以我的理解是,它扫描文件以找到与第一个指定参数 (5) 匹配的行号,并执行指定的操作,直到达到与第二个参数 (10) 匹配的行号。但是,当我反转范围时,即:
sed -n '10,5 p' < file
它只打印了文件中的第 10 行。那么,我关于 sed 操作方式的假设是否不正确?是什么导致第 10 行被偶数打印,因为指定的 'range' 甚至不是实际有效范围?
谢谢!
如果您指定一个范围,其中开始和结束是一个行号,则结束行号必须大于起始行号。如果结束行号小于或等于起始行号,则该范围将仅适用于起始行号。手册页说明了这一点,
我首先想到你想以相反的顺序打印范围内的行,在这种情况下你可以通过管道传输到 tac
:
sed -n '5,10p' file | tac
如果您只想使用 (GNU) sed
,您可以使用以下脚本:
sed -n '5,10{x;H};${x;s/\n$//p}'
如果当前行在 5
和 10
之间的范围内,sed 将使用 x
交换模式缓冲区和保持缓冲区。现在当前行位于保持缓冲区的顶部。之后,模式缓冲区(先前的保持缓冲区)将使用 H
附加到保持缓冲区。将感兴趣的行以相反的顺序存储在保持缓冲区中。在输入结束 $
时,我们交换保持缓冲区和模式缓冲区,替换末尾的换行符,最后使用 p
打印它。使用 -n
命令行选项禁用正常输出。
来自the man page:
An address range can be specified by specifying two addresses separated by a comma (,). An address range matches lines starting from where the first address matches, and continues until the second address matches (inclusively).
If the second address is a regexp, then checking for the ending match will start with the line following the line which matched the first address: a range will always span at least two lines (except of course if the input stream ends).
If the second address is a number less than (or equal to) the line matching the first address, then only the one line is matched.
注意第一段中的“包括”一词,然后是第三段中较长的解释。
为什么?不要在这里对我们进行形而上学...:-)