【问题标题】:Create symbolic links transforming file names - Bash Script创建转换文件名的符号链接 - Bash 脚本
【发布时间】:2014-03-01 21:13:05
【问题描述】:

我有一个 bash 脚本,它将遍历一个目录来获取每个文件名。我想做的是为这些文件创建一些符号链接。除了我想更改链接名称。

示例 1:

文件名: testFile.so.3.4.5

ln -s testFile.so.3.4.5 testFile.so.3
ln -s testFile.so.3 testFile.so

示例 2:

文件名: testLink.so.4.4

ln -s testLink.so.4.4 testLink.so.4 
ln -s testLink.so.4 testLink.so

所以我需要转换文件名两次。第一次删除除了*.so 之后的第一个数字之外的所有内容。第二次删除*.so之后的所有内容。

这是我目前所拥有的。我知道这并不多:

#! /bin/bash

# clear any info on screen
clear

# greeting
echo "Starting the script!"

# loop through all files in the directory
for f in *
do
    echo "Processing: $f"
done

我对 bash 和文件名转换有点陌生,所以任何帮助或指导将不胜感激。

【问题讨论】:

    标签: linux bash shell sed transform


    【解决方案1】:

    结合使用 bash extended regular expressionsparameter expansion

    for file in *.so.*
    do
    regex='(.*\.so\.[^.]*)\..*'
    if [[ $file =~ $regex ]]
    then
      tempfile="${BASH_REMATCH[1]}"
      ln -s "$file" "$tempfile"
      ln -s "$tempfile" "${tempfile%.*}"
    fi
    done
    

    【讨论】:

    • 太棒了!这正是我所需要的。
    【解决方案2】:

    也更一般地说,只使用参数扩展:

    for f in *.so.*.*
    do
      if [ -e "$f" ]; then
        base=${f%".${f#*.so.*.*}"}
        ln -s "$f" "$base"
        ln -s "$base" "${base%.*}"
      fi
    done
    

    【讨论】:

      【解决方案3】:

      或更笼统地说:

      files='libfoo.so.1.2.3.4.5 libbar.so libqux.so.1'
      
      for f in $files; do
        while test ${f##*.} != so; do
          link=${f%.*}
          ln -s $f $link
          f=$link
        done
      done
      

      这将创建libfoo.so.1.2.3.4 -> libfoo.so.1.2.3.4.5libfoo.so.1.2.3 -> libfoo.so.1.2.3.4libfoo.so.1.2 -> libfoo.so.1.2.3libfoo.so.1 -> libfoo.so.1.2libfoo.so -> libfoo.so.1libqux.so -> libqux.so.1; libbar.so 将被忽略。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-18
        • 1970-01-01
        • 1970-01-01
        • 2012-10-03
        • 2010-10-02
        • 2013-08-26
        • 1970-01-01
        • 2012-01-10
        相关资源
        最近更新 更多