![](/img/trans.png)
[英]bash rename file/add integer in filename with various extensions in multiple subdirectories
[英]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.