Pet*_*nak 11 command-line text-processing
想象一下这样的命令的输出
44444
55555
11111
22222
33333
Run Code Online (Sandbox Code Playgroud)
我怎样才能拉出前 N 行(上例中的前两行)并将它们附加到最后,但不使用临时文件(所以只使用管道)?
11111
22222
33333
44444
55555
Run Code Online (Sandbox Code Playgroud)
类似的东西| sed -n '3,5p;1,2p'(这显然不起作用,因为 sed 不关心命令的顺序)。
don*_*sti 13
只需将这些行复制到保持缓冲区(然后删除它们),并在最后一行将保持缓冲区的内容附加到模式空间:
some command | sed '1,NUMBER{ # in this range
H # append line to hold space and
1h # overwrite if it's the 1st line
d # then delete the line
}
$G' # on last line append hold buffer content
Run Code Online (Sandbox Code Playgroud)
有了gnu sed你可以把它写成
some command | sed '1,NUMBER{H;1h;d;};$G'
Run Code Online (Sandbox Code Playgroud)
这是 ol' 的另一种方式ed(它将r的输出some command读入文本缓冲区,然后在m最后一行1,NUMBER之后添加行$):
ed -s <<IN
r ! some command
1,NUMBERm$
,p
q
IN
Run Code Online (Sandbox Code Playgroud)
请注意 - 正如所指出的 - 如果输出少于NUMBER+1 行,这些都会失败。更可靠的方法是(gnu sed语法):
some command | sed '1,NUMBER{H;1h;$!d;${g;q;};};$G'
Run Code Online (Sandbox Code Playgroud)
这个只会删除该范围内的行,只要它们不是最后一行 ( $!d) - 否则它会用保持缓冲区内容 ( g)覆盖模式空间,然后quits (在打印当前模式空间之后)。
Sté*_*las 11
一种awk方法:
cmd | awk -v n=3 '
NR <= n {head = head $0 "\n"; next}
{print}
END {printf "%s", head}'
Run Code Online (Sandbox Code Playgroud)
与@don_crisstised方法相比的一个好处是,如果输出的n行数或更少,它仍然可以工作(输出行数)。
小智 6
我有xclip并且有了它可以通过这种方式完成:
./a_command | xclip -in && xclip -o | tail -n +3 && xclip -o | head -n 2
Run Code Online (Sandbox Code Playgroud)
这是它的描述:
xclip - command line interface to X selections (clipboard)
NAME
xclip - command line interface to X selections (clipboard)
SYNOPSIS
xclip [OPTION] [FILE]...
DESCRIPTION
Reads from standard in, or from one or more files, and makes the data available as an X selection for pasting into X applications. Prints current X selection to standard out.
-i, -in
read text into X selection from standard input or files (default)
-o, -out
prints the selection to standard out (generally for piping to a file or program)
Run Code Online (Sandbox Code Playgroud)