更改文件扩展名
changing filename extension
我正在尝试将文件扩展名从 .xlsx 更改为 .csv。
到目前为止我已经有了这个语法并且工作得很好。
raw_file=test_file.xlsx
echo "${raw_file%.xlsx}.csv"
test_file.csv
但如果我尝试将 .xlsx 分配给变量,它就不再起作用了。
f=.xlsx
echo "${raw_file%.$f}.csv"
test_file.xlsx.csv
我做错了什么?
您可以使用 basename
命令,例如
raw_file=test_file.xlsx
f=.xlsx
echo $(basename "$raw_file" "$f").csv
# -> test_file.csv
但请记住,basename
还会从文件名中删除任何前导目录名称。
问题是你有“.”在变量(“.xlsx”)和替换表达式(“.$f”)中,所以它试图删除“..xlsx”。您只需要将句点放在这些地方之一,然后就可以了:
$ raw_file=test_file.xlsx
$ extwithoutdot=xlsx
$ echo "${raw_file%.$extwithoutdot}.csv" # Here the "." is in the expression
test_file.csv
$ extwithdot=.xlsx
$ echo "${raw_file%$extwithdot}.csv" # Here the "." is in the variable
test_file.csv
$ echo "${raw_file%.$extwithdot}.csv" # Here the "." is in both -- it fails
test_file.xlsx.csv
我正在尝试将文件扩展名从 .xlsx 更改为 .csv。
到目前为止我已经有了这个语法并且工作得很好。
raw_file=test_file.xlsx
echo "${raw_file%.xlsx}.csv"
test_file.csv
但如果我尝试将 .xlsx 分配给变量,它就不再起作用了。
f=.xlsx
echo "${raw_file%.$f}.csv"
test_file.xlsx.csv
我做错了什么?
您可以使用 basename
命令,例如
raw_file=test_file.xlsx
f=.xlsx
echo $(basename "$raw_file" "$f").csv
# -> test_file.csv
但请记住,basename
还会从文件名中删除任何前导目录名称。
问题是你有“.”在变量(“.xlsx”)和替换表达式(“.$f”)中,所以它试图删除“..xlsx”。您只需要将句点放在这些地方之一,然后就可以了:
$ raw_file=test_file.xlsx
$ extwithoutdot=xlsx
$ echo "${raw_file%.$extwithoutdot}.csv" # Here the "." is in the expression
test_file.csv
$ extwithdot=.xlsx
$ echo "${raw_file%$extwithdot}.csv" # Here the "." is in the variable
test_file.csv
$ echo "${raw_file%.$extwithdot}.csv" # Here the "." is in both -- it fails
test_file.xlsx.csv