更改文件扩展名

时间:2018-04-24 06:15:18

标签: bash unix echo

我正在尝试将文件扩展名从.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
我做错了什么?

2 个答案:

答案 0 :(得分:1)

问题是你有“。”在变量(“。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

答案 1 :(得分:0)

您可以使用raw_file=test_file.xlsx f=.xlsx echo $(basename "$raw_file" "$f").csv # -> test_file.csv 命令,例如

basename

但请记住, let passingDict : [String:Any] = [ "fname" : YourValue, "lname":YourValue, "email" : YourValue, "password" : YourValue, "countryCode": YourValue, "mobileNumber": YourValue, "verificationType":YourValue, ] let signup_url = ApiList.base_url + ApiList.signup_url singletonclass.instance.Post_API_Call(passingDict, Url: signup_url, HittingApi: "SIGN_UP_URL") func Post_API_Call(_ Parame: NSDictionary, Url: String, HittingApi: String) { var Api_Resp_Err = String() var Api_Resp_Dict = NSDictionary() do { let jsonData = try JSONSerialization.data(withJSONObject: Parame, options: []) let fullListURL = Url let url = URL(string: Url)! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.httpBody = jsonData let task = URLSession.shared.dataTask(with: request) { data,response,error in if error != nil { DispatchQueue.main.async(execute: { Api_Resp_Err = (error?.localizedDescription)! }) return } do { if let responseJSON = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary { if responseJSON.count > 0 { DispatchQueue.main.async(execute: { let statusCode = responseJSON.object(forKey: "code") as? String ?? "" let message = responseDict.object(forKey: "Message") as? String ?? "" }) } else { } } else { DispatchQueue.main.async(execute: { Api_Resp_Err = "Data Issue" }) } } catch { DispatchQueue.main.async(execute: { Api_Resp_Err = "Catch Issue" }) } } task.resume() } catch { DispatchQueue.main.async(execute: { //print("Server Issue catch II") }) } } 还会从文件名中删除所有前导目录名称。