简体   繁体   English

Bash脚本从文件名中删除前导空格

[英]Bash script to remove leading white spaces from files names

So I have a bunch of files like: 所以我有一堆文件,例如:

 Aaron Lewis - Country Boy.cdg
 Aaron Lewis - Country Boy.mp3
 Adele - Rolling In The Deep.cdg
 Adele - Rolling In The Deep.mp3
 Adele - Set Fire To The Rain.cdg
 Adele - Set Fire To The Rain.mp3
 Band Perry - Better Dig Two.cdg
 Band Perry - Better Dig Two.mp3
 Band Perry - Pioneer.cdg
 Band Perry - Pioneer.mp3

and I need to have the leading whitespace removed in bash or fish script. 并且我需要删除bash或fish脚本中的前导空格。

To remove the leading white space char in the file names you provided you can use: 要在您提供的文件名中删除前导空格字符,可以使用:

 IFS=$'\n'
 for f in $(find . -type f -name ' *')
 do 
     mv $f ${f/\.\/ /\.\/}
 done

This: 这个:

  • changes the IFS to only be newline characters; 将IFS更改为仅换行符; this way it does not choke on the whitespaces in the file names. 这样,它不会阻塞文件名中的空格。
  • finds all files starting with a whitespace in the current directory. 在当前目录中查找所有以空格开头的文件。
  • moves each file to a file name without the leading whitespace, using bash substring substitution. 使用bash子字符串替换将每个文件移动到没有前导空格的文件名。
for x in \ * ; do
  mv "$x" `echo "$x" | sed "s/^ +//"`
done

This is quick and dirty. 这又快又脏。

cat <file> | sed -e 's/^[ ]*//'

should do the trick. 应该可以。 Capture stdout and write to a file. 捕获标准输出并写入文件。

You don't need sed for this. 您不需要sed Just use bash string function: 只需使用bash字符串函数:

for file in /path/to/files/*; 
    do mv "$file" "${file# *}"; 
done

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

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