【问题标题】:Rename output file in uppercase without the extensions bash以大写形式重命名输出文件,不带扩展名 bash
【发布时间】:2022-01-06 10:44:58
【问题描述】:

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

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

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

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

这是我的输出重定向的外壳:

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

【问题讨论】:

  • f='test.des.utf8'; nf="${f%%.*}"; nf="${nf@U}.cpy"; echo "$nf"

标签: bash shell unix filenames


【解决方案1】:

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"

【讨论】:

  • 我可以像这样在一行中做到这一点吗:“${filename^^%%.*}.cpy”?
  • @YoussefHammouma 如果您知道要提前删除的完整扩展名,例如 "$(basename "${filename^^}" .DST.UTF8).cpy"
  • 或者如果你可以使用 zsh 代替 bash,"${(U)filename%%.*}.cpy"
  • 也可以完全用awk完成,包括处理所有文件
  • @LéaGris 你几乎可以说任何编程语言,是的。
【解决方案2】:

如果使用 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/*

【讨论】:

    猜你喜欢
    • 2016-02-25
    • 2018-01-11
    • 2016-12-06
    • 1970-01-01
    • 2018-03-02
    • 2012-01-02
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多