sed:从文件中删除字母数字字

sed:从文件中删除字母数字字,sed,text-formatting,Sed,Text Formatting,我有一个包含大量文本的文件,我想做的是删除所有字母数字单词 Example of words to be removed: gr8 2006 sdlfj435ljsa 232asa asld213 ladj2343asda asd!32 我能做到这一点的最佳方法是什么?如果目标实际上是删除所有字母数字字(完全由字母和数字组成的字符串),那么这个sed命令将起作用。它用零替换所有字母数字字符串 sed 's/[[:alnum:]]*//g' < inputfile

我有一个包含大量文本的文件,我想做的是删除所有字母数字单词

Example of words to be removed:

gr8  
2006  
sdlfj435ljsa  
232asa  
asld213  
ladj2343asda
asd!32  

我能做到这一点的最佳方法是什么?

如果目标实际上是删除所有字母数字字(完全由字母和数字组成的字符串),那么这个
sed
命令将起作用。它用零替换所有字母数字字符串

sed 's/[[:alnum:]]*//g' < inputfile
sed的//[:alnum:]*//g'
请注意,除了
alnum
之外,还可以使用其他字符类(请参见
man 7 regex

对于给定的示例数据,只剩下6个空行和一个
(因为这是示例数据中唯一的非字母数字字符)。这就是你想要做的吗?

解决方案:

BEGIN { # Statement that will be executed once at the beginning.
    FS="[ \t]" # Set space and tab characters to be treated as word separator.
}
# Code below will execute for each line in file.
{
    x=1  # Set initial word index to 1 (0 is the original string in array)
    fw=1 # Indicate that future matched word is a first word. This is needed to put newline and spaces correctly.
    while ( x<=NF )
    {
        gsub(/[ \t]*/,"",$x) # Strip word. Remove any leading and trailing white-spaces.
        if (!match($x,"^[A-Za-z0-9]*$")) # Print word only if it does not match pure alphanumeric set of characters.
        {
            if (fw == 0)
            {
                printf (" %s", $x) # Print the word offsetting it with space in case if this is not a first match.
            }
            else
            {
                printf ("%s", $x) # Print word as is...
                fw=0 # ...and indicate that future matches are not first occurrences
            }
        }
        x++ # Increase word index number.
    }
    if (fw == 0) # Print newline only if we had matched some words and printed something.
    {
        printf ("\n")
    }
}
对于您的文件,它将生成:

asd!32
对于此类更复杂的情况:

awk -f ./test.awk ./data.txt
gr8
2006
sdlfj435ljsa
232asa  he!he lol
asld213  f
ladj2343asda
asd!32  ab acd!s
。。。它将产生以下结果:

he!he
asd!32 acd!s
希望能有帮助。
祝你好运

如果要删除由字母和数字组成的所有单词,只保留由所有数字或字母组成的单词:

sed 's/\([[:alpha:]]\+[[:digit:]]\+[[:alnum:]]*\|[[:digit:]]\+[[:alpha:]]\+[[:alnum:]]*\) \?//g' inputfile
例如:

$ echo 'abc def ghi 111 222 ab3 a34 43a a34a 4ab3' | sed 's/\<\([[:alpha:]]\+[[:digit:]]\+[[:alnum:]]*\|[[:digit:]]\+[[:alpha:]]\+[[:alnum:]]*\) \?//g'
abc def ghi 111 222

$echo'abc def ghi 111 222 ab3 a34 43a a34a 4ab3'| sed's/\假设示例文本的唯一输出是
2006
,并且每行有一个单词:

 sed '/[[:alpha:]]\+/{/[[:digit:]]\+/d}' /path/to/alnum/file
输入 输出
使用
/^$/d'
命令将清除输出。例如,
sed'/[:alpha:]\+/{[:digit:]\+/s/*//g}'alnum
将在单行上返回
2006
alpha
,并接收注释。我已经五年没有看这个答案了,但是现在我已经根据你的评论看了,我删除了这一行,而不是用一个空行来代替它。干得好,这一行甚至删除了命令链接。我印象深刻,同时也学到了一些新东西+1.
$ cat alnum
gr8
2006
sdlFj435ljsa
232asa
asld213
ladj2343asda
asd!32
alpha
$ sed '/[[:alpha:]]\+/{/[[:digit:]]\+/d}' ./alnum
2006
alpha