简体   繁体   English

在 bash 脚本中将 *.txt.csv 文件重命名为 .csv

[英]renaming *.txt.csv files to .csv in bash script

I have.txt files, which I am taking as $item and then I am changing the encoding with我有 .txt 文件,我将其作为 $item ,然后我正在更改编码

iconv -f $currentEncoding -t $targetEncoding "$item" -o "$item.tmp"

then I am saving it again to txt file using然后我将它再次保存到 txt 文件使用

 mv "$item.tmp" "$item.txt";

next I am trimming a few things in txt file and saving it as a csv file with接下来我将在 txt 文件中修剪一些内容并将其保存为 csv 文件

 tr -d '"' < "$item.txt" > "$item.csv";

but eventually my files are getting stored with extension "*.txt.csv" - I want them to be just.csv - can anyone help me please what I am doing wrong or what could I change.但最终我的文件以扩展名“* .txt.csv”存储 - 我希望它们只是.csv - 谁能帮我请教我做错了什么或者我可以改变什么。 Thanks谢谢

From what I understand, your $item already has.txt in the value.据我了解,您的 $item 价值中已经有.txt 。 So, if you list your files after each command, you should see intermediate files like因此,如果您在每个命令之后列出文件,您应该会看到中间文件,例如

xyz.txt.tmp
xyz.txt.txt
xyz.txt.csv

So, when you set the item variable, just do ${item%%.*} as shown below and it should work as expected.因此,当您设置 item 变量时,只需执行 ${item%%.*} 如下所示,它应该可以按预期工作。

item=xyz.txt               
item="${item%%.*}"    
echo $item        
xyz

Run:跑:

for f in *.txt.csv; do mv $f ${f/.txt./.}; done

If the variable $f contains the string item.txt.csv , the expression ${f/.txt./.} removes .txt from the file name and gives only the string item.csv .如果变量$f包含字符串item.txt.csv ,则表达式${f/.txt./.}从文件名中删除.txt并仅给出字符串item.csv

Caution: if one of the filenames contain spaces, the for statement will not work as expected.注意:如果其中一个文件名包含空格, for语句将无法按预期工作。

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

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