bash - 将文件名的前 4 个字符存储到变量中

标签 bash

以下代码是我正在编写的脚本的一部分。现在,为了这个脚本的目的,我假设 ./src 中只有 1 个文件,所以这个循环应该只执行一次。现在,在某处的循环中,我想获取 $f 的前 4 个字符(文件名)并将其存储在另一个变量中。我知道有 cut 命令,但我不确定这里是否或如何使用它,因为我认为 cut 用于文件内容,而不是文件本身。

for f in `ls ./src`
do
    echo $f
    cd tmp
    f="../src/$f"
    sh "$f"
done

最佳答案

来自 http://tldp.org/LDP/abs/html/string-manipulation.html

Substring Extraction

${string:position} Extracts substring from $string at $position.

If the $string parameter is "*" or "@", then this extracts the positional parameters, [1] starting at $position.

${string:position:length} Extracts $length characters of substring from $string at $position.

示例

shortName=${f:0:4}

玩得开心!

关于bash - 将文件名的前 4 个字符存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534301/

相关文章:

perl - 管道元素或将它们指定为 Perl 单行代码中的参数有什么区别?

linux - Bash 脚本访问重定向|管道输入

从 bash 脚本运行时出现 Python 语法错误

linux - bash:使用解压缩更改存档中的文件名

string - Bash - 如何替换特定索引处的字符(包括索引零)

regex - 如何从 Bash 中的正则表达式中提取多个环境变量?

linux - Bash - 使用从文件中读取的条件中断循环

bash - 如何从特定日期开始通过 goaccess 获取 access_log 摘要?

Bash 脚本 : write CPU utilization to file (Ubuntu)

linux - 什么时候用引号括起 shell 变量?