How would I mix patterns and numeric ranges in sed (or any similar tool - awk for example)? What I want to do is match certain lines in a file, and delete the next n lines before proceeding, and I want to do that as part of a pipeline.
6 Answers
227
votes
12
votes
6
votes
Simple awk
solutions:
Assume that the regular expression to use for finding matching lines is stored in shell variable $regex
, and the count of lines to skip in $count
.
If the matching line should also be skipped ($count + 1
lines are skipped):
... | awk -v regex="$regex" -v count="$count" \
'$0 ~ regex { skip=count; next } --skip >= 0 { next } 1'
If the matching line should not be skipped ($count
lines after the match are skipped):
... | awk -v regex="$regex" -v count="$count" \
'$0 ~ regex { skip=count; print; next } --skip >= 0 { next } 1'
Explanation:
-v regex="$regex" -v count="$count"
definesawk
variables based on shell variables of the same name.$0 ~ regex
matches the line of interest{ skip=count; next }
initializes the skip count and proceeds to the next line, effectively skipping the matching line; in the 2nd solution, theprint
beforenext
ensures that it is not skipped.--skip >= 0
decrements the skip count and takes action if it is (still) >= 0, implying that the line at hand should be skipped.{ next }
proceeds to the next line, effectively skipping the current line
1
is a commonly used shorthand for{ print }
; that is, the current line is simply printed- Only non-matching and non-skipped lines reach this command.
- The reason that
1
is equivalent to{ print }
is that1
is interpreted as a Boolean pattern that by definition always evaluates to true, which means that its associated action (block) is unconditionally executed. Since there is no associated action in this case,awk
defaults to printing the line.
3
votes
3
votes
2
votes
This solution allows you to pass "n" as a parameter and it will read your patterns from a file:
awk -v n=5 '
NR == FNR {pattern[$0]; next}
{
for (patt in pattern) {
if ($0 ~ patt) {
print # remove if you want to exclude a matched line
for (i=0; i<n; i++) getline
next
}
}
print
}
' file.with.patterns -
The file named "-" means stdin for awk, so this is suitable for your pipeline