【问题标题】:Bash - Get first 3 letters of filename [duplicate]Bash - 获取文件名的前 3 个字母 [重复]
【发布时间】:2014-12-07 21:29:34
【问题描述】:

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

我试过了:

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

if ((curfilefirst3 == curfile2first3 )); then

....

但我觉得有问题,我该如何解决?

谢谢。

【问题讨论】:

    标签: bash


    【解决方案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
    

    打印相同 所以,有效

    【讨论】:

      【解决方案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可能是个好主意

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-28
        • 2023-03-13
        • 2015-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多