Monday, April 29, 2024
7
rated 0 times [  7] [ 0]  / answers: 1 / hits: 4989  / 2 Years ago, fri, january 7, 2022, 1:04:29

I have a text file and I want to delete random lines from a range. Here is an example:



Line 1: abcd
Line 2: efgh
Line 3: ijkl
Line 4: mnop
Line 5: qrst
Line 6: uvwxyz


Out of these six, I want to randomly delete, say, 3.



How to get that done? It would be great if there is a solution in vim, so one can apply it on different ranges.


More From » command-line

 Answers
1

Here's a solution using sed:



sed -i $((start + RANDOM % range))d filename.txt


where:




  • start is the beginning line number of your range

  • range (or end-start is the number of lines to include from start)

  • sed -i -Nd tells sed to delete line N in the input file

  • RANDOM is bash's random number generator; a special shell variable that holds a random integer between 0 and 32767 when you use it.



So, for example, to delete a random line between lines 90 and 120 in file test.txt, you'd use:



sed -i $((90 + RANDOM % 30))d test.txt

[#36889] Saturday, January 8, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
enefiama

Total Points: 43
Total Questions: 125
Total Answers: 102

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
enefiama questions
;