简体   繁体   English

如何使用Shell脚本删除文本文件中具有相同单词并连续增加数字的字符串?

[英]How to delete a string with the same word and consecutively increasing number in a text file using a shell script?

For example I have: 例如,我有:

Hello1 :
Hello2 : 
Hello3 :

How Could I delete all of these with a shell script. 如何使用Shell脚本删除所有这些。 The number reaches up all the way to 1000. 这个数字一直到1000。

sed -i '/^Hello[[:digit:]]\+\>/d' file.txt

或者,如果要输出到其他文件:

sed '/^Hello[[:digit:]]\+\>/d' file.txt > newfile.txt

If you wish to delete all the lines that contain only Hello(number) : use below : 如果要删除仅包含Hello(number) :所有行,请使用以下命令:

Sample Input in file file 样本输入

Hell
Hello1 :
No hello stuff here
Unjulating stuff
Hello2 :
Some sentence
Hello99 :

Script 脚本

sed -Ei '/^Hello[[:digit:]]+ :$/d' file

Sample Output in the modified file 修改后的file中的示例输出

Hell
No hello stuff here
Unjulating stuff
Some sentence

What happens above 上面发生了什么

  1. Using the ^ in the pattern we check for the beginning of the line. 使用模式中的^ ,我们检查行的开头。
  2. We check the pattern Hello(number) : using Hello[[:digit:]]+ :$ . 我们使用Hello[[:digit:]]+ :$检查模式Hello(number) : Note that I used -E to enable sed extended regular expressions so I need not escape the + ie ( \\+ ). 请注意,我使用-E启用sed扩展正则表达式,因此无需转义+即( \\+ )。 Here [[:digit:]] is a class which contains all the decimal digits and + is used to check if the pattern before it matches at least one time. 此处[[:digit:]]是一个类,它包含所有十进制数字,而+用于检查之前的模式是否至少匹配一次。
  3. Check the end of the line using $ 使用$检查行尾
  4. For a matched pattern, delete it line using the d option 对于匹配的模式,请使用d选项将其删除
  5. I have also used the sed inplace edit option -i so that the changes are directly saved to the file. 我还使用了sed inplace edit选项-i以便将更改直接保存到文件中。

If you wish to change the a line the begins with Hello(number) : then use the below script 如果您想更改一行,则以Hello(number) :开头Hello(number) :然后使用以下脚本

sed -Ei '/^Hello[[:digit:]]+ :/d' file

You might have notices that I just removed the $ , so our pattern matches any line that starts with Hello(number) : 您可能已经注意到,我刚刚删除了$ ,所以我们的模式匹配以Hello(number) :开头的任何行Hello(number) :

Hope this helps. 希望这可以帮助。

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

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