Bash:从包含数字的字符串中删除单词

时间:2015-06-24 10:46:48

标签: bash shell

在bash中如何执行字符串重命名删除包含数字的所有单词:

name_befor_proc="art-of-medusa-feefacc0-c75e-4846-9ccf-7463d5944061.jpg"

结果:

name_after_proc="art-of-medusa.jpg"

5 个答案:

答案 0 :(得分:1)

在sed中,删除包含数字的-之间的所有内容。

sed 's/[^-]*[0-9][^-\.]*-\{0,1\}//g;s/-\././' test
art-of-medusa.jpg

答案 1 :(得分:0)

您可以使用gnu-awk:

s="art-of-medusa-feefacc0-c75e-4846-9ccf-7463d5944061.jpg"
name_after_proc=$(awk -v RS='[.-]' '!/[[:digit:]]/{printf r $1} {r=RT}' <<< "$s")

echo "$name_after_proc"
art-of-medusa.jpg

答案 2 :(得分:0)

我想没有通用的解决方案,你也可以使用以下python脚本来处理你的特定用例

name = "art-of-medusa-feefacc0-c75e-4846-9ccf-7463d5944061.jpg"
ext  = name.split(".")[1]
def contains_number(word):
    for i in "0123456789":
        if i in word:
            return False
    return True
final = '-'.join([word for word in name.split('-') if contains_number(word)])
if ext not in final:
    final += "."+ext

print final

输出:

art-of-medusa.jpg

答案 3 :(得分:0)

这不是微不足道的!

awk -F"." -v sep="-" '
      {n=split($1,a,sep)
       for (i=1; i<=n; i++)
            {if (a[i] ~ /[0-9]/) delete a[i]}
       n=length(a)
       for (i in a)
            printf "%s%s", a[i], (++c<n?sep:"")
       printf "%s%s\n", FS, $2}'

拆分字符串(直到点)并循环切片。如果包含数字,请将其删除。然后,重新加入阵列并相应地打印。

测试

$ awk -F"." -v sep="-" '{n=split($1,a,sep); for (i=1; i<=n; i++) {if (a[i] ~ /[0-9]/) delete a[i]}; n=length(a); for (i in a) printf "%s%s", a[i], (++c<n?sep:""); printf "%s%s\n", FS, $2}' <<< "art-of-medusa-feefacc0-c75e-4846-9ccf-7463d5944061.jpg"
art-of-medusa.jpg

使用"art-of-medusa-feefacc0-c75e-4846-9ccf-7463d5944061-a-23-b.jpg"进行测试,以确保其他字词也匹配:

$ awk -F"." -v sep="-" '{n=split($1,a,sep); for (i=1; i<=n; i++) {if (a[i] ~ /[0-9]/) delete a[i]}; n=length(a); for (i in a) printf "%s%s", a[i], (++c<n?sep:""); printf "%s%s\n", FS, $2}' <<< "art-of-medusa-feefacc0-c75e-4846-9ccf-7463d5944061-a-23-b.jpg"
art-of-medusa-a-b.jpg

答案 4 :(得分:0)

两种可能的解决方案:

  1. 使用Sed:

    sed 's/[a-zA-Z0-9]*[0-9][a-zA-Z0-9]*/ /g' filename

  2. 使用grep:

    grep -wo -E [a-zA-Z]+ foo | xargs filename