【问题标题】:How to remove file extension using linux and store first the filename如何使用linux删除文件扩展名并首先存储文件名
【发布时间】:2021-12-13 01:57:34
【问题描述】:

假设我有一个像 1.txt ....100.txt 这样的 100 个文件。现在我想删除 .txt 并计算文件名的平均值(因为它们是数字)。我查看了这个Linux: remove file extensions for multiple files,但还是有点困惑。

【问题讨论】:

  • 扩展名总是.txt吗?如果是这样basename path/to/100.txt .txt 会给你100

标签: bash


【解决方案1】:

让我们创建一些示例文件:

$ for i in {1..10}; do touch "$RANDOM.txt"; done
$ ls
15158.txt  15964.txt  17123.txt  21123.txt  22209.txt  29456.txt  29826.txt  4168.txt  4287.txt  6787.txt

现在,将文件名存储在数组中,将表达式构建为字符串,并将其发送到单个 bc 调用:

files=(*.txt)

expr="(0"
for f in "${files[@]}"; do expr+=" + ${f%.txt}"; done
expr+=") / ${#files[@]}"

echo "$expr"
echo "scale=3; $expr" | bc

输出

(0 + 15158 + 15964 + 17123 + 21123 + 22209 + 29456 + 29826 + 4168 + 4287 + 6787) / 10
16610.100

更简洁:

join() { local IFS=$1; shift; echo "$*"; }
files=(*.txt)
printf -v expr "(%s)/%d" "$(join + "${files[@]%.txt}")" ${#files[@]}
echo "$expr"
echo "scale=3; $expr" | bc
(15158+15964+17123+21123+22209+29456+29826+4168+4287+6787)/10
16610.100

【讨论】:

    【解决方案2】:

    您可以使用basename <path_to_file> <extension> 删除目录部分和扩展名,这样您就只剩下号码了。

    例子:

    #!/bin/bash
    
    shopt -s extglob                     # extended globbing
    
    filecount=0
    sum=0
    
    for file in some_dir/+([0-9]).txt    # loop over the files (using extended globbing)
    do
        num=$(basename "$file" .txt)     # strip away dir and extension
        (( sum += num ))                 # sum up the numbers
        (( ++filecount ))                # count the number of files
    done
    
    mean="NaN"                           # used if filecount is 0
    if (( filecount > 0 ))
    then
        # calculate mean with 2 digits of precision
        mean=$(echo "scale=2;$sum/$filecount" | bc)
    
    fi
    echo "$mean"
    

    【讨论】:

      【解决方案3】:

      我会做这样的事情

      numbers=`ls | sed 's/.txt//g' | xargs`
      echo $numbers 应该显示“1 2 3 .... 100”

      sum=0; count=0
      for i in $numbers; do
      sum=$(echo "$sum + $i" | bc)
      ((count++))
      done
      
      avg=$(echo "$sum / $count" | bc)
      echo $avg
      

      【讨论】:

      • 如果数字都是整数,就像 OP 一样,您可以在 bash 中对它们求和,然后使用 bc 除以求均值。 sum=$((sum + i))
      猜你喜欢
      • 2011-05-29
      • 2015-01-25
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      相关资源
      最近更新 更多