【问题标题】:listing files in the directory using grep使用 grep 列出目录中的文件
【发布时间】:2012-01-26 19:53:52
【问题描述】:

列出/usr/bin文件名 包含小写英文字母的所有文件 字符 并且还包含单词 file 作为(连续的)子字符串。

例如,fileprofiles 是这样的文件,但 git-ls-files 不是。

这是我的确切问题,我只能使用greplscatwc

ls /usr/bin/ | grep '[^-]*file'

这是我到目前为止得到的,输出如下。我不知道如何显示例如file,因为* is zero or more occurences。也不知道如何在正则表达式中放入小写字母..

check-binary-files
clean-binary-files
desktop-file-install
desktop-file-validate
ecryptfs-rewrite-file
file
filep
git-cat-file
git-diff-files
git-ls-files
git-merge-file
git-merge-one-file
git-unpack-file
lockfile
nsrfile
pamfile
pcprofiledump
pnmfile
ppufiles
profiles

【问题讨论】:

  • 为什么要投反对票? OP 已将其列为作业,说明了预期结果的要求并展示了他的尝试。

标签: regex unix grep


【解决方案1】:
ls /usr/bin/ | grep --regex '^[[:lower:]]*file[[:lower:]]*$'

^ 和 $ 分别匹配字符串的开头和结尾。

【讨论】:

    【解决方案2】:

    在这种情况下,使用 lsgrep 进行管道传输确实是多余的。你可以使用find:

    $> find /usr/bin -regex "/usr/bin/[a-z]*file[a-z]*" -type f -printf "%f\n"
    profiles
    keditfiletype
    inifile
    dotlockfile
    pamfile
    pnmfile
    file
    konsoleprofile
    

    【讨论】:

    • 问题是“我只能使用 grep ls cat wc”,但如果这些限制不存在,这绝对是要走的路。
    【解决方案3】:
    ls -1 /usr/bin | grep '^[a-z]*file[a-z]*$'
    

    ls -1 确保文件在一行中列出。 ^$ 是行首和行尾的符号,这是您所缺少的(否则它可以匹配文件名的子字符串)

    【讨论】:

      【解决方案4】:

      使用 -P 选项,表示 Perl 正则表达式,所以最后你的命令看起来像:

      ls /usr/bin | grep -P '[a-z]file'
      
      insider@gfl ~/test/bin$ ls
      123file             desktop-file-install   file          git-diff-files  git-merge-one-file  nsrfile        pnmfile   testlist
      check-binary-files  desktop-file-validate  filep         git-ls-files    git-unpack-file     pamfile        ppufiles
      clean-binary-files  ecryptfs-rewrite-file  git-cat-file  git-merge-file  lockfile            pcprofiledump  profiles
      insider@gfl ~/test/bin$ ls . | grep -P '[a-z]file'
      lockfile
      nsrfile
      pamfile
      pcprofiledump
      pnmfile
      ppufiles
      profiles
      

      【讨论】:

        猜你喜欢
        • 2013-01-20
        • 2016-08-22
        • 1970-01-01
        • 2012-12-09
        • 2016-07-11
        • 2013-07-23
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        相关资源
        最近更新 更多