如何使用tail、head命令与管道符打印文件中指定行区间的内容?
tail, head, and Pipes Great question! Let's walk through exactly how to do this with tail, head, and pipes—no fancy tools needed. Here are two straightforward approaches to print lines 5 through 8 of a .txt file:
Approach 1: Trim from the top first, then grab from the middle
Use head to get all lines up to your end line (line 8), then pipe that output to tail to start printing from your start line (line 5):
head -n 8 yourfile.txt | tail -n +5
Breakdown:
head -n 8 yourfile.txt: Extracts the first 8 lines of the file (since line 8 is our upper bound)|: The pipe sends the output of the first command directly into the next onetail -n +5: Takes the input fromheadand prints everything starting from line 5 to the end of that input—leaving us with lines 5-8 exactly.
Approach 2: Skip the early lines first, then trim the end
Alternatively, start by skipping lines before your start line with tail, then use head to cap it at your end line:
tail -n +5 yourfile.txt | head -n 4
Breakdown:
tail -n +5 yourfile.txt: Skips the first 4 lines and prints everything from line 5 onward to the end of the file|: Pipes that extended output toheadhead -n 4: Takes the first 4 lines of that input (which are lines 5,6,7,8 of the original file) and stops there—perfect for our target range.
Example Test Case
If your file example.txt looks like this:
Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10
Running either command above will output:
Line 5 Line 6 Line 7 Line 8
A quick note: Make sure you count the number of lines in your range correctly! For lines X to Y, the number of lines to grab with head in Approach 2 is Y - X + 1 (in this case, 8-5+1=4).
内容的提问来源于stack exchange,提问作者lambozsolty

