Home > Net >  Delete first N char from a text file
Delete first N char from a text file

Time:10-31

I have large data file with some data as :

01 01 00 2c 00 82 03 00 02 00 00 00 07 08 07 08   
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08   
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08   
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08   
0f 08 08 08 0a 08 07 08 0f 08 08 08 08 08 08 08   
08 08 08 08 08 07 08 07 0a 07 07 07 0f 07 08 07   
08 07 08 07 08 07 08 07 08 07 08 07 0a 07 07 07   
..
..... 

I would like to delete every first n characters from every 6th row

I have found a command :

sed 's/^.\{,n\}//' file

But this command deletes first n chars from each row, which I do not want to happen.

Could someone suggest the right command?

CodePudding user response:

awk -v n=17 '(NR%6)==1 { print substr($0, n); next } 1' file

The condition uses modulo arithmetic on the line number NR to select every sixth line, starting from the first. The final 1 causes the other lines to be printed normally.

You haven't revealed the value of n so I guessed.

CodePudding user response:

GNU sed allows you to use address in form of

first~step

(...)matches every stepth line starting with line first(...)

therefore 1~6 does pertain to 1st, 7th, 13th and so on lines, 2~6 pertains to 2nd, 8th, 14th and so on lines, let file.txt content be

01 01 00 2c 00 82 03 00 02 00 00 00 07 08 07 08   
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08   
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08   
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08   
0f 08 08 08 0a 08 07 08 0f 08 08 08 08 08 08 08   
08 08 08 08 08 07 08 07 0a 07 07 07 0f 07 08 07   
08 07 08 07 08 07 08 07 08 07 08 07 0a 07 07 07   
..
.....

and n be equal to 5 then, you might do

sed '1~6 s/^.....//' file.txt

which gives output

 00 2c 00 82 03 00 02 00 00 00 07 08 07 08   
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08   
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08   
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08   
0f 08 08 08 0a 08 07 08 0f 08 08 08 08 08 08 08   
08 08 08 08 08 07 08 07 0a 07 07 07 0f 07 08 07   
 08 07 08 07 08 07 08 07 08 07 0a 07 07 07   
..
.....

(tested GNU sed 4.7)

  • Related