Deleting specific lines from text file via scripting

Hi,

I'm trying to search for some number and from that line, i need to delete the 5th line exactly.

Eg:
Consider below as text file data:

10000
a
b
c
d
e
.
.
.
10000
w
q
t
y
s

in the above i need to delete 'e','s' and do the same for all matched numbers and update the file.

What i tried is using sed i'm able to find the line number for that matched number but i'm stuck in moving to line no. 5 from 1st matched record.

Can someone kindly suggest some way to do achieve this.

awk '$0 ~ patt {n = NR} NR != n+5' patt='10000' file
1 Like

Thanks. it works cool.

isn't that possible with sed ?

sed '/10000/{n;n;n;n;n;d}' file

I found a flaw in that 'awk' code..

lets say file as c.txt :

10000
a
b
c
d
e
..
10000
a
b
c
d
e
..
.

It works fine for the above file as the first set of data is that of same pattern we provide in that code..

Now lets say as d.txt :

20000
a
b
c
d
e
.
.
10000
a
b
c
d
e
.
.

It removes the 'e' from first set of lines also..

Hope you getting the issue.

---------- Post updated 04-11-14 at 09:05 AM ---------- Previous update was 04-10-14 at 10:44 AM ----------

Can someone help me in this ?

---------- Post updated at 09:06 AM ---------- Previous update was at 09:05 AM ----------

Can someone help me out for this issue ?

Try

awk '$0 ~ PATT {P=NR+5} NR!=P' PATT=10000 file
1 Like

I was trying to do this to all files ending with .txt in my destination directory using the following code :

cd /my_destination_dir/

for i in `ls *.txt`
do
awk '$0 ~ pat {n=NR+5} NR!=n' pat=10000 $i > $i
done

the given awk code works well for a single file even made with run time arguments but to make this dynamic for all files its not getting achieved.

What my code does is - making all .txt files to empty.

Can you please tell where i'm going wrong in the code

You can't overwrite an input file by redirection immediately - it will be erased when opening for output before anything has been read. Use an intermediate file.
Try (untested):

awk '$0 ~ PATT {P=NR+5} NR!=P {print >FILENAME".tmp"}' PATT=10000 *.txt

and then rename the temp files.

okay..

even the following might work:

awk '$0~pat {n=NR+5} NR!=n' pat='10000' $1 > $2
mv -i $2 $1

and running the above by:

sh script_name file_name tmp_file_name

Right ?