简体   繁体   English

Bash:如何使用sed删除除字母和数字之外的所有字符?

[英]Bash: How to use sed to remove all characters except letters and numbers?

First off, I'm still learning about regular expression, I have googled about this but still doesn't work. 首先,我仍在学习正则表达式,已经在Google上进行了搜索,但仍然无法正常工作。

How do I remove all characters except letters and numbers in a variable with sed ? 如何使用sed删除变量中除字母和数字以外的所有字符? For example I have this text file: 例如,我有这个文本文件:

MytextOnly !@#!text@@32423#@$text#%$#text%#t23432ext$32342%^-_+-=-_++_;:"'][}}{|\/

How do I show only letters and numbers? 如何仅显示字母和数字?

You can use: 您可以使用:

sed 's/[^[:alnum:]]\+//g' file
MytextOnlytext32423texttextt23432ext32342

[^[:alnum:]] property will find all non-alphanumerical characters. [^[:alnum:]]属性将查找所有非字母数字字符。


EDIT: Based on comments below: 编辑:基于以下评论:

sed 's~[^[:alnum:]/]\+~~g' file
MytextOnlytext32423texttextt23432ext32342/

Using grep 使用grep

grep -o '[[:alnum:]]' file

agree, no the perfect output, but everything is there 同意,没有完美的输出,但是一切都在那里

Using tr 使用tr

$ tr -d -c '[:alnum:]' < file
MytextOnlytext32423texttextt23432ext32342

If you also want to keep forward slashes: 如果您还想保持正斜杠:

$ tr -d -c '[:alnum:]/' < file
MytextOnlytext32423texttextt23432ext32342/

For a python solution, see https://stackoverflow.com/a/5843560/297323 有关python解决方案,请参见https://stackoverflow.com/a/5843560/297323

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

相关问题 如何替换除字母,数字,正斜杠和反斜杠之外的所有字符 - How to replace all characters except letters, numbers, forward and back slashes 正则表达式匹配除字母和数字之外的所有字符 - Regex to match all characters except letters and numbers 替换字母,数字和空格以外的所有字符 - Replace all characters except letters, numbers and spaces 如何在 python 中使用 Regex 删除除字母之外的所有字符 - How do I use Regex in python to remove ALL characters EXCEPT letters 在Windows上sed,删除除指定字符外的所有字符 - sed on windows, remove all characters except specified preg_replace删除除破折号,字母,数字,空格和下划线以外的所有字符 - preg_replace to remove all characters except dashes, letters, numbers, spaces, and underscores 如何删除所有隐藏字符(冒号,数字和“ AM”或“ PM”除外) - How to remove all hidden characters except colons, numbers and 'AM' or 'PM' 如何从字符串中删除除数字、“,”和“.”之外的所有字符使用红宝石? - How to remove all characters from string except numbers, "," and "." using Ruby? 删除字符串中不是字母或数字的所有字符 - Remove all characters that are not letters or numbers in a String 正则表达式删除除数字以外的所有特殊字符? - Regex remove all special characters except numbers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM