创build符号链接转换文件名 – Bash脚本

我有一个bash脚本,将通过获取每个文件名的目录循环。 我想要做的是为这些文件创build一些符号链接。 除了我想改变链接名称。

例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和文件名转换有点新,所以任何帮助或指导将不胜感激。

使用bash 扩展正则表达式和参数扩展的组合

 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 

另外更一般地说,仅使用参数扩展:

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

或者更一般地说:

 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将被忽略。