在Unix中用head/tail/awk删除指定行并修改原文件
Got it, let's work through this problem since we're limited to just head, tail, and awk on HP-UX's ksh shell. Here's a reliable way to get the exact result you need—keeping the first line, removing lines 2-3, dropping the second and third last lines, and writing everything back to the original file.
Step-by-Step Command Breakdown
First, let's outline the approach: we'll use awk to count total lines, then filter the lines we want to keep, and finally replace the original file safely.
Backup your file first! Always a good idea to avoid accidental data loss:
cp your_file.txt your_file.txt.bakGet the total number of lines in the file using
awk:total_lines=$(awk 'END{print NR}' your_file.txt)This uses
awk'sENDblock to print the total number of records (lines) after processing the entire file.Filter and write the desired lines to a temporary file, then replace the original:
awk -v total="$total_lines" ' NR == 1 || (NR >= 4 && NR <= total - 3) || NR == total ' your_file.txt > temp_file.txt && mv temp_file.txt your_file.txt
What Each Part Does
Let's break down the awk condition:
NR == 1: Keeps the very first line of the file.NR >= 4 && NR <= total - 3: Keeps all lines starting from the 4th line up to the 4th last line (since we need to skip the 3rd and 2nd last lines). For example, if the file has 10 lines,total -3is 7—so lines 4-7 are kept, skipping 8 (3rd last) and 9 (2nd last).NR == total: Keeps the final line of the file, regardless of its line number.
Example Test Case
If your input file looks like this:
Line 1 (keep)
Line 2 (delete)
Line 3 (delete)
Line 4 (keep)
Line 5 (keep)
Line 6 (delete, 3rd last)
Line 7 (delete, 2nd last)
Line 8 (keep, last line)
After running the commands, the output file will be:
Line 1 (keep)
Line 4 (keep)
Line 5 (keep)
Line 8 (keep, last line)
This approach works reliably even if the total number of lines changes, since we're calculating it dynamically.
内容的提问来源于stack exchange,提问作者Minsec

