【问题标题】:An alternative: cut -d <string>?另一种选择:cut -d <string>?
【发布时间】:2014-04-01 12:00:41
【问题描述】:

当我输入ls 时,我得到:

aedes_aegypti_upstream_dremeready_all_simpleMasked_random.fasta
anopheles_albimanus_upstream_dremeready_all_simpleMasked_random.fasta
anopheles_arabiensis_upstream_dremeready_all_simpleMasked_random.fasta
anopheles_stephensi_upstream_dremeready_all_simpleMasked_random.fasta
culex_quinquefasciatus_upstream_dremeready_all_simpleMasked_random.fasta

我想通过管道将其转换为 cut (或通过其他方式),以便我只得到:

aedes_aegypti
anopheles_albimanus
anopheles_arabiensis
anopheles_stephensi
culex_quinquefasciatus

如果 cut 接受一个字符串(多个字符)作为分隔符,那么我可以使用:

cut -d "_upstream_" -f1

但这是不允许的,因为 cut 只使用单个字符作为分隔符。

【问题讨论】:

    标签: bash shell parsing text cut


    【解决方案1】:

    awk 允许字符串作为分隔符:

    $ awk -F"_upstream_" '{print $1}' file
    aedes_aegypti
    anopheles_albimanus
    anopheles_arabiensis
    anopheles_stephensi
    culex_quinquefasciatus
    drosophila_melanogaster
    

    注意,对于给定的输入,您还可以使用 cut_ 作为分隔符并打印前两条记录:

    $ cut -d'_' -f-2 file
    aedes_aegypti
    anopheles_albimanus
    anopheles_arabiensis
    anopheles_stephensi
    culex_quinquefasciatus
    drosophila_melanogaster
    

    sedgrep 也可以。例如,这个grep 使用前瞻打印从行首到找到_upstream 的所有内容:

    $ grep -Po '^\w*(?=_upstream)' file
    aedes_aegypti
    anopheles_albimanus
    anopheles_arabiensis
    anopheles_stephensi
    culex_quinquefasciatus
    drosophila_melanogaster
    

    【讨论】:

    • 完美答案!
    【解决方案2】:

    如果您只想要第一个字段,您可以在纯 bash 中执行此操作:

    ls | while read line; do echo "${line%%_upstream_*}"; done
    

    【讨论】:

    • 这么多替代方法,我从每一个中都学到了一点,谢谢!
    • @hello_there_andy 没问题,就是这样
    【解决方案3】:

    你也可以使用 sed:

    sed -i.bak 's/_upstream.*//' file
    

    结果:

    aedes_aegypti
    anopheles_albimanus
    anopheles_arabiensis
    anopheles_stephensi
    culex_quinquefasciatus
    drosophila_melanogaster
    

    注意:这也会将原始文件创建为 file.bak 的备份。

    【讨论】:

      【解决方案4】:

      类似于@Tom Fenech - 使用bash parameter expansion/substring removal - 但使用for 循环:

      $ ls
      aedes_aegypti_upstream_dremeready_all_simpleMasked_random.fasta
      anopheles_albimanus_upstream_dremeready_all_simpleMasked_random.fasta
      anopheles_arabiensis_upstream_dremeready_all_simpleMasked_random.fasta
      anopheles_stephensi_upstream_dremeready_all_simpleMasked_random.fasta
      culex_quinquefasciatus_upstream_dremeready_all_simpleMasked_random.fasta
      drosophila_melanogaster_upstream_dremeready_all_simpleMasked_random.fasta
      
      $ for file in *; do
      > echo "${file%%_upstream_*}"
      > done
      aedes_aegypti
      anopheles_albimanus
      anopheles_arabiensis
      anopheles_stephensi
      culex_quinquefasciatus
      drosophila_melanogaster
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-21
        • 2020-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        相关资源
        最近更新 更多