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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15534301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:55:35  来源:igfitidea点击:

Storing the first 4 characters of a filename into a variable

bash

提问by zyxxwyz

This follwing code is part of a script I am writing. Now, for the purposes of this script, I am assuming there is only 1 file in ./src, so this loop should only execute once. Now, in the loop somewhere, I want to take the first 4 characters of $f (the filename) and store it in another variable. I know there is the cut command but I'm not sure if or how that would be used here because I thought cut was used for contents of files, not the files themselves.

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

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

回答by Michel Feldheim

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

来自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.

子串提取

${string:position}从 $position 处的 $string 中提取子字符串。

如果 $string 参数是“*”或“@”,那么这将提取位置参数,[1] 从 $position 开始。

${string:position:length}从 $position 处的 $string 中提取子字符串的 $length 个字符。

Example

例子

shortName=${f:0:4}

Have fun!

玩得开心!

回答by anubhava

You can use pure bash way:

您可以使用纯 bash 方式:

${parameter:offset:length}

i.e. to get first chars of $HOMEvariable:

即获取$HOME变量的第一个字符:

echo ${HOME:0:4}

btw your script is also faulty (never parse ls output). It should be like this:

顺便说一句,您的脚本也有问题(永远不要解析 ls 输出)。应该是这样的:

for f in ./src/*
do
    echo $f
    cd tmp
    f="../src/$f"
    first4=${f:0:4}
    sh "$f"
done