Bash - 获取前3个文件名

时间:2014-10-13 10:33:23

标签: bash

我有一个小的bash脚本并且有$ file和$ file2变量。这是文件,我想得到这个文件名的前3个字母。我想比较一下:

我试过了:

curfile=$(basename $file)  
curfilefirst3=${curfile:0:3}
curfile2=$(basename $file2)
curfile2first3=${curfile2:0:3}

if ((curfilefirst3 == curfile2first3 )); then

....

但我认为有问题,我该如何解决?

谢谢。

2 个答案:

答案 0 :(得分:2)

您在比较中缺少$字符串,您需要使用"包装每个字符串,并使用[]包装整个表达式:

file="this.txt"
file2="that.txt"

curfile=$(basename $file)
curfilefirst3=${curfile:0:3}

curfile2=$(basename $file2)
curfile2first3=${curfile2:0:3}

echo $curfile2first3
echo $curfilefirst3

if [ "$curfile2first3" == "$curfilefirst3" ]
then
   echo "same!"
else
   echo "different!"
fi

阅读bash conditionals

可能是个好主意

答案 1 :(得分:1)

子串提取

$ {string:position}在$ position从$ string中提取子字符串。 但是,如果应该使用[而不是(如:

if [ $curfilefirst3 == $curfile2first3 ]; then

更正后的版本:

#!/bin/bash
file=abcdef
file2=abc123456
curfile=$(basename $file)
curfilefirst3=${curfile:0:3}
curfile2=$(basename $file2)
curfile2first3=${curfile2:0:3}
echo $curfilefirst3
echo $curfile2first3
if [ $curfilefirst3 = $curfile2first3 ]; then
echo same
else
echo different
fi

它打印相同 所以,工作