I am trying to delete a file's contents from a supplied line number using sed. The problem is that sed isn't accepting the variable I supply to it
line_num=$(grep -n "debited" file.csv | sed -n '2 s/:.*//p') && sed -i.bak "$line_num,$d" file.csv
The idea is to delete all lines from a file after & including the second occurence of the pattern.
I'm not stubborn with sed
. Awk
& perl
could do too.
CodePudding user response:
Seems like you want to delete the rest of the file after a second showing of a pattern (debited
), and I'd guess that you want to keep the whole line with the pattern.
Then can just truncate it, ising tell for the length
perl -wE'while (<>) {
if ( ($cnt = /debited/) == 2 ) { truncate $ARGV, tell; exit }
}' file
Here the $ARGV variable has the "current" file (when reading from <>). Feel free to introduce a variable with the pattern instead of the literal (debited
), based on your context.
This can be made to look far nicer in a little script but it seems that a command-line program ("one-liner") is needed in the question.
CodePudding user response:
you're doing lot's of unnecessary steps, this will do what you want.
$ awk '/debited/{c } c==2{exit}1' file
delete second occurrence of the pattern and everything after it.