sed
provides a simpler way:
... | sed '/some stuff/ {N; s/^.*\n//; :p; N; $q; bp}' | ...
This way you delete first occurrence.
If you want more:
sed '1 {h; s/.*/iiii/; x}; /some stuff/ {x; s/^i//; x; td; b; :d; d}'
, where count of i
is count of occurrences (one or more, not zero).
Multi-line Explanation
sed '1 {
# Save first line in hold buffer, put `i`s to main buffer, swap buffers
h
s/^.*$/iiii/
x
}
# For regexp what we finding
/some stuff/ {
# Remove one `i` from hold buffer
x
s/i//
x
# If successful, there was `i`. Jump to `:d`, delete line
td
# If not, process next line (print others).
b
:d
d
}'
In addition
Probably, this variant will work faster, 'cos it reads all rest lines and print them in one time
sed '1 {h; s/.*/ii/; x}; /a/ {x; s/i//; x; td; :print_all; N; $q; bprint_all; :d; d}'
As result
You can put this code into your .bashrc
(or config of your shell, if it is other):
dtrash() {
if [ $# -eq 0 ]
then
cat
elif [ $# -eq 1 ]
then
sed "/$1/ {N; s/^.*\n//; :p; N; \$q; bp}"
else
count=""
for i in $(seq $1)
do
count="${count}i"
done
sed "1 {h; s/.*/$count/; x}; /$2/ {x; s/i//; x; td; :print_all; N; \$q; bprint_all; :d; d}"
fi
}
And use it this way:
# Remove first occurrence
cat file | dtrash 'stuff'
# Remove four occurrences
cat file | dtrash 4 'stuff'
# Don't modify
cat file | dtrash
awk 'NR>2'
? – Jan 06 '17 at 04:11cat a.txt | sed -e '1,2d' | tac | sed -e '1,1d' | tac
where1,2d
removes 1st two lines which is column name and hyphen row and1,1d
removes the result count row. And check it out in http://unix.stackexchange.com/questions/37790/how-do-i-delete-the-first-n-lines-of-an-ascii-file-using-shell-commands – RBB Jan 06 '17 at 04:13grep
unfortunately can not do it. The closest option would be to limit the number of lines shown before you ignore them:grep -v -m 10
would show the first 10 matches and ignore the rest. – Julie Pelletier Jan 06 '17 at 04:22vi
known asex
. If you include example input output I'll elucidate further. – Wildcard Jan 11 '17 at 22:28