Linux:从文件名中获取特定字段

标签 linux bash

我目前正在学习 Linux bash 脚本:

我的文件夹中有具有以下文件名模式的文件:

ABC01_-12ab_STRINGONE_logicMatches.txt
DEF02_-12ab_STRINGTWO_logicMatches.txt
JKL03_-12ab_STRINGTHREE_logicMatches.txt

我想将 STRINGONE、STRINGTWO 和 STRINGTHREE 提取为列表。为了看看我的想法是否有效,我想先将我的结果回显到 bash。

我的 bash 脚本的代码(在文件所在的文件夹中执行):

#!/bin/bash
for element in 'folder' do out='cut -d "_" -f2 $element | echo $out' done

实际结果:

error: unexpected end of file

期望的结果:

STRINGONE
STRINGTWO
STRINGTHREE
(echoed in bash)

最佳答案

你的想法是对的。但是文件通配(查找文本文件)和命令替换(运行 cut 命令)的语法是错误的。你需要做

for file in folder/*.txt; 
    # This condition handles the loop exit if no .txt files are found, and
    # not throw errors
    [ -f "$file" ] || continue
    # The command-substitution syntax $(..) runs the command and returns the
    # result out to the variable 'out'
    out=$(cut -d "_" -f3 <<< "$file")
    echo "$out"
done

关于Linux:从文件名中获取特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46974041/

相关文章:

linux - Linux 进程/线程可以在不通过 do_exit() 的情况下终止吗?

linux - git 克隆 GnuTLS 接收错误 (-9) : A TLS packet with unexpected length was received

linux - 结合ccze和grep?

PHP网站,我应该开发成Linux发行版而不是Windows吗?

用C程序连接Mysql

bash - 在 docker 中运行时优雅地停止 Solr

bash - grep 中双引号中的减号被识别为一个选项

python - autojump如何捕获访问过的路径

linux - bash 硬链接(hard link)不起作用

linux - 将命令输出存储到变量时如何保留换行符?