复制文件时,将固定的子字符串移动到文件名的末尾

时间:2018-12-17 01:26:03

标签: bash shell file

我的文件夹中有一堆文件,文件名以MyTest开头:

MyTestHttpAdaptor.class
MyTestJobCreation.class

我想使用以下名称创建这些文件的副本:删除MyTest前缀,并添加一个Test后缀:

MyHttpAdaptorTest.class
MyJobCreationTest.class

这怎么办?

1 个答案:

答案 0 :(得分:1)

for file in MyTest*.*; do    # iterate over files that start with MyTest and have a .
  ext=${file##*.}            # remove everything before the last . to get the extension
  basename=${file%.*}        # remove everything *after* the last . to get the "basename"
  new_basename=${basename#MyTest}      # remove the prefix to get the *new* basename
  new_file="${new_basename}Test.$ext"  # combine that prefix with the "Test" suffix & ext.
  [[ -e $new_file ]] || cp -- "$file" "$new_file"  # copy if result does not already exist
done

${file##*.}${file%.*}${basename#MyTest}parameter expansion的示例,其中删除了前缀和后缀。

相关问题