简体   繁体   English

如何删除与模式匹配的特定数量的随机行

[英]How to delete a specific number of random lines matching a pattern

I have an svg file with a grid of dots represented by lines that have the word use in them. 我有一个svg文件,其中包含点阵网格,点阵由其中包含单词use的线表示。 I would like to delete a specific number of random lines matching that use pattern, then save a new version of the file. 我想删除特定数量的use模式匹配的随机行,然后保存文件的新版本。 This answer was very close. 这个答案非常接近。

So it will be a combination of this (delete one random line in a specific range): 因此,这将是这些的组合(在特定范围内删除一条随机行):

sed -i '.svg' $((9 + RANDOM % 579))d /filename.svg 

and this (delete all lines matching pattern use ): 这(删除所有与pattern匹配的行use ):

sed -i '.svg' /use/d /filename.svg

In other words, the logic would go something like this: 换句话说,逻辑将如下所示:

sed -i delete 'x' number of RANDOM lines matching 'use' from 'input.svg' and save to 'output.svg'

I'm running these commands from Terminal on a Mac and am inexperienced with syntax so formatting the command for that would be ideal. 我是从Mac上的Terminal运行这些命令的,对语法没有经验,因此格式化该命令将是理想的选择。

Delete each line containing "use" with a probability of 10%: 删除每一行包含“使用”的概率为10%:

awk '!/use/ || rand() > 0.10' file

Randomly delete exactly one line containing "use": 随机删除只包含“ use”的一行:

awk -v n="$(( RANDOM % $(grep -c "use" file) ))" '!/use/ || n-- != 0' file

Here's an example invocation: 这是一个示例调用:

$ cat file
some string
a line containing "use"
another use-ful line
more random data

$ awk -v n="$(( RANDOM % $(grep -c "use" file) ))" '!/use/ || n-- != 0' file
some string
another use-ful line
more random data

One of the lines containing use was removed. 删除了包含use的行之一。

This might work for you: (GNU sed & sort): 这可能对您有用:(GNU sed和sort):

sed -n '/\<use\>/=' file | sort -r | head -5 | sed 's/$/d/' | sed -i.bak -f - file

Extract the line numbers of the lines containing the word use from the file. 从文件中提取包含单词use的行的行号。 Randomly sort those line numbers then take the first say 5 and build a sed script to delete them from the original file. 随机排序这些行号,然后使用第一个说5并构建sed脚本以将其从原始文件中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM