【问题标题】:Trying to grep part of a file name in shell script?试图在 shell 脚本中 grep 文件名的一部分?
【发布时间】:2013-05-23 13:57:22
【问题描述】:

我有一个非常简单的 grep 问题,但似乎无法解决。我有几个这样的文件:

sample.txt
sample7.doc.txt
another_sample.sample.lst.txt
three.txt

...我只想抓住“.txt”之前的所有内容。我试图在这样的 shell 脚本中执行此操作:

ame=`echo $1 | grep -Po "^[A-Za-z0-9]+"`

...但当然,这只会返回第一个“点”之前的部分。有人可以帮忙修改这个正则表达式吗?

【问题讨论】:

    标签: regex shell grep


    【解决方案1】:

    不需要正则表达式:

    $ basename sample.txt .txt
    sample
    

    或使用任何与 POSIX 兼容的外壳:

    $ echo "$a"
    sample.txt
    
    $ y=${a%.txt}
    
    $ echo "$y"
    sample
    

    【讨论】:

    • 很好,我不知道'basename'
    • 这是一个很好的工具,可以放在你的实用腰带上,还有dirname
    • @Kent 那是 Bourne Shell (sh),而且一直都是。
    • 对于包含空格或其他 IFS 字符(或 glob 表达式)的名称,需要引用扩展才能正常工作。
    【解决方案2】:

    试试这个:

    grep -Po '.*(?=\.txt$)'
    

    【讨论】:

      【解决方案3】:
      1. 删除 .txt

        name=echo $1|sed 's/.txt$//'

      2. 使用基本名称

        name=echo $fullname|basename .txt

      【讨论】:

      • 因为没有在变量周围使用双引号而被诱惑为 -1。
      【解决方案4】:

      这是重命名文件的脚本。

      将文件名作为参数传递

      !/bin/bash

      mv $1 $(echo $1 | awk -F.txt '{print $1}')

      【讨论】:

        猜你喜欢
        • 2017-03-15
        • 1970-01-01
        • 2013-12-08
        • 1970-01-01
        • 2015-04-21
        • 2019-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多