以大写形式重命名输出文件,不带扩展名 bash

Rename output file in uppercase without the extensions bash

在 shell 中,我浏览了几个文件以重新格式化它们,因此我生成了一个包含文件名 + .cpy 扩展名的输出。

例如我有 test.des.utf8 生成到 test.des.utf8.cpy,我想做的是从 test.des.utf8 到TEST.cpy.

我尝试过类似的方法,但它对我不起作用:

"$f" "${f%.txt}.text"

这是我的 shell 输出重定向:

for f in $SOURCE_DIRECTORY 
do 
    b=$(basename "$f")
    echo "Generating $f file in copy.."; 
    awk -F ';' '
=="TABLE" && ==" " {
  printf "01 %s.\n\n", ;
  next
}
{
  result = 
  if ( ~ /^Numérique [0-9]+(\.[0-9]+)?$/) {
    nr=split(,a,"[ .]")
    result = "PIC 9(" a[2] ")"
    if (nr == 3) {
      result = result ".v9(" a[3] ")"
    }    
  }
  sub(/CHAR/,"PIC X", result);
  printf "   * %s.\n\n     05 %s %s.\n\n", , , result;
}' "$f" > "$TARGET_DIRECTORY/$b.cpy"
done

bash 参数扩展使得变量的大写扩展和删除结果字符串的一部分变得容易:

filename=test.des.utf8

# Upper-cased version of filename
newfilename="${filename^^}"
# Remove everything from the first . to the end and add a new extension
newfilename="${newfilename%%.*}.cpy"

# Remove echo when happy with results
echo cp "$filename" "$newfilename"

如果使用 Gnu Awk,您可以使用这个独立的 awk 脚本处理所有文件:

myAwkScript

#!/usr/bin/env -S awk -f

BEGIN {
  FS=";"
  targetDir="./"
}

# Before processing each file passed as argument
BEGINFILE {
  # Split the file path
  i=split(FILENAME, splitpath, "/")

  # File name part without path is last element
  name = splitpath[i]

  # Split file name on dot
  split(name, splitname, ".")

  # Compose outputPath to targetDir with:
  # Uppercase first part before dot and .cpy suffix
  outputPath = targetDir toupper(splitname[1]) ".cpy"

  # Erase the content of the outputPath
  printf "" > outputPath
}

# Your original awk script will process each line of each file
=="TABLE" && ==" " {
  # Changed this to append to the outputPath file
  printf "01 %s.\n\n",  >> outputPath
  next
}
{
  result = 
  if ( ~ /^Numérique [0-9]+(\.[0-9]+)?$/) {
    nr=split(,a,"[ .]")
    result = "PIC 9(" a[2] ")"
    if (nr == 3) {
      result = result ".v9(" a[3] ")"
    }    
  }
  sub(/CHAR/,"PIC X", result)

  # Changed this to append to the outputPath file
  printf "   * %s.\n\n     05 %s %s.\n\n", , , result >> outputPath
}

使脚本可执行:

chmod +x ./myAwkScript

运行 处理所有文件的脚本:

./myAwkScript somewhere/*