bash - 替代 : cut -d <string>?

标签 bash shell parsing text cut

当我输入 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 只将单个字符作为分隔符。

最佳答案

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

关于bash - 替代 : cut -d <string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22785250/

相关文章:

c++ - Charniak 解析器错误

c - FFMPEG:视频解码器解析器的工作原理

linux - 在 bash 头痛中转义变量

bash - 如何使用 FFmpeg 将视频拆分为 <2.5GB 的部分

python - 读取-未知选项

bash - <<END_SCRIPT 同时通过 bash 连接到 FTP

javascript - 将html文本字段解析为javascript

linux - 在 Bash 中将一个程序的输出转换为另一个程序的输入

Bash函数杀死进程

bash - 如何获取htpasswd的退出状态?