1

Suppose i have a file with this structures

1001.txt
1002.txt
1003.txt
1004.txt
1005.txt
2001.txt
2002.txt
2003.txt
...

Now how can I delete first 10 numbers of line which start with '2'? There might be more than 10 lines start with '2'.

I know I can use grep '^2' file | wc -l to find number of lines which start with '2'. But how to delete the first 10 numbers of line?

jww
  • 97,681
  • 90
  • 411
  • 885
pwan
  • 687
  • 3
  • 9
  • 16
  • You might find a clue here https://stackoverflow.com/questions/23696871/how-to-remove-only-the-first-occurrence-of-a-line-in-a-file-using-sed – JeffUK Jul 11 '17 at 16:05

3 Answers3

2

You can pipe your list through this Perl one-liner:

perl -p -e '$_="" if (/^2/ and $i++ >= 10)'
amphetamachine
  • 27,620
  • 12
  • 60
  • 72
1

Another in awk. Testing with value 2 as your data only had 3 lines of related data. Replace the latter 2 with a 10.

$ awk '/^2/ && ++c<=2 {next} 1' file
1001.txt
1002.txt
1003.txt
1004.txt
1005.txt
2003.txt
.
.
.

Explained:

$ awk '/^2/ && ++c<=2 {   # if it starts with a 2 and counter still got iterations left
    next                  # skip to the next record
} 1                       # (else) output
' file
James Brown
  • 36,089
  • 7
  • 43
  • 59
0

awk alternative:

awk '{ if (substr($0,1,1)=="2") { count++ } if ( count > 10 || substr($0,1,1)!="2") { print $0 } }' filename

If the first character of the line is 2, increment a counter. Then only print the line if count is greater than 10 or the first character isn't 2.

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18