我会使用
sed '2,7!d' file1 | tac
tac 只是反向(按行)重复给出的内容。
至于制表符分隔的部分,使用 sed 有很多方法可以做到这一点。其中之一是
sed '2,7!d' | tac | sed '1h; 1!H; $!d; x; s/\n/\t/g'
这会在保持缓冲区中组装完整的输入,然后将其交换到模式空间中并用制表符替换其中的所有换行符:
1h # first line: save to hold buffer
1!H # subsequent lines: append to hold buffer
$!d # if more input is to read, stop here (don't print anything)
x # otherwise: swap in assembled lines
s/\n/\t/g # replace newlines with tabs.
您也可以考虑在此步骤中使用 tr,但尾随的换行符使这不像最初想象的那么简单。
或者,您可以使用 sed 一次性完成所有操作:
sed '2,7 { G; x; }; $!d; x; s/\n$//; s/\n/\t/g' file1
这有点棘手:
2,7 { # In lines 2 to 7:
G # Append the hold buffer to the pattern space
# this is originally a blank line and later the reverse
# of the lines already read
x # then swap it back into the hold buffer
}
$!d # If the input has not ended, stop here (print nothing)
x # When the whole input is consumed, swap the assembled
# reverse lines back in
s/\n$// # remove the trailing newline
s/\n/\t/g # then replace the newlines with tabs
这有点折腾哪种方法更好。后者在使用 sed 方面仍然有些理智,但更复杂的 sed 脚本的蝙蝠侠解码器环属性已经显示出来。坦率地说,我很伤心,因为我对 sed 情有独钟,在这种情况下考虑放弃 sed 以换取更长但更易读的替代方案(例如awk)并不是一个坏主意:
awk 'NR == 2, NR == 7 { result = $0 sep result; sep = "\t" } END { print result }' file1