简体   繁体   中英

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. The number reaches up all the way to 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 :

Sample Input in 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

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:]]+ :$ . Note that I used -E to enable sed extended regular expressions so I need not escape the + ie ( \\+ ). 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.
  3. Check the end of the line using $
  4. For a matched pattern, delete it line using the d option
  5. I have also used the sed inplace edit option -i so that the changes are directly saved to the file.

If you wish to change the a line the begins with Hello(number) : then use the below script

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) :

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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