Bash-remove-n-match: Difference between revisions

From I Will Fear No Evil
Jump to navigation Jump to search
(Created page with "Really unique problem and resolution using awk found in reddit. [https://www.reddit.com/r/bash/comments/qva5bm/delete_n_occurrence_of_a_pattern/?%24deep_link=true&correlation_...")
 
mNo edit summary
 
(One intermediate revision by the same user not shown)
Line 4: Line 4:


<pre>
<pre>
input text1.txt:
input text1.txt has:
hi 1
hi 1
hi 2
hi 2
Line 23: Line 23:
awk '!/hi/||++n>4'
awk '!/hi/||++n>4'
</pre>
</pre>
Possible alternate that would still require some work:
<pre>
count=4 awk -e '
    /hi [[:digit:]]+/ && s++ < ENVIRON["count"] { next };
    {print};
' << EOT
hi 1
hi 2
hi 3
hi 4
hi 5
hello
EOT
</pre>
[[Category:Bash]]

Latest revision as of 19:25, 17 May 2023

Really unique problem and resolution using awk found in reddit. [1]


input text1.txt has:
hi 1
hi 2
hi 3
hi 4
hi 5
hello

I want to delete 4 lines containing 'hi'
wanted output:

hi 5
hello

Unique answer:

awk '!/hi/||++n>4'

Possible alternate that would still require some work:

count=4 awk -e '
    /hi [[:digit:]]+/ && s++ < ENVIRON["count"] { next };
    {print};
' << EOT 
hi 1
hi 2
hi 3
hi 4
hi 5
hello
EOT