在 bash 中结合 basename {} 和 string 的操作

eno*_*noy 2 bash find shell-script filenames

我想编写一个脚本来查找所有.cpp.cc. 搜索将从开始路线 R 递归完成,这是脚本的参数。

如果没有写入参数,R 将是实际目录。

我写过:

#!/bin/bash

R=.
if [[ $# == 1 ]]
then
    echo "$# == 1"
    if [[ -d $1 ]]
    echo "$1 is directory"
    then
        R=$1
    else
        printf "Error $1 should be a directory"
        exit 1
    fi
find $R -name "*.cpp" -exec sh -c 'mv {} $(dirname {})${$(basename {})%.cpp}".cc" ' \;
exit 0
else
    printf "Invocation is: $0 directory"
    exit 1
fi
Run Code Online (Sandbox Code Playgroud)

但是我知道我在 find 行中遇到了麻烦,因为我不知道如何表达我想在使用 {} 时删除扩展名并附加新的扩展名

cuo*_*glm 6

不要通过直接操作来做这样的事情{}

您已经使用了 inline sh,因此将其{}作为参数传递给它,而且您根本不需要使用basename

find "$R" -name "*.cpp" -type f -exec sh -c '
  for f do
    mv -- "$f" "${f%.*}.cc"
  done
' sh {} +
Run Code Online (Sandbox Code Playgroud)

请注意,您必须双引号$R,否则会导致安全漏洞。