繁体   English   中英

将 output 文件重命名为大写,不带扩展名 bash

[英]Rename output file in uppercase without the extensions bash

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

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

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

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

这是我的 shell 和 output 重定向:

for f in $SOURCE_DIRECTORY 
do 
    b=$(basename "$f")
    echo "Generating $f file in copy.."; 
    awk -F ';' '
$1=="TABLE" && $3==" " {
  printf "01 %s.\n\n", $2;
  next
}
{
  result = $2
  if ($2 ~ /^Numérique [0-9]+(\.[0-9]+)?$/) {
    nr=split($2,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", $3, $1, 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
$1=="TABLE" && $3==" " {
  # Changed this to append to the outputPath file
  printf "01 %s.\n\n", $2 >> outputPath
  next
}
{
  result = $2
  if ($2 ~ /^Numérique [0-9]+(\.[0-9]+)?$/) {
    nr=split($2,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", $3, $1, result >> outputPath
}

使脚本可执行:

chmod +x ./myAwkScript

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

./myAwkScript somewhere/*

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM