通过用下划线替换逗号和空格来更改多个文件名

ali*_*rth 7 files

我的文件格式为

Country, City S1.txt
Run Code Online (Sandbox Code Playgroud)

例如

USA, Los Angeles S1.txt
USA, San Francisco S3.txt
UK, Glouchester S4.txt
Argentina, Buenos Aires S7.txt
Run Code Online (Sandbox Code Playgroud)

我希望将它们更改为

Country_City_S1.txt
Run Code Online (Sandbox Code Playgroud)

例如

USA_Los_Angeles_S1.txt
USA_San_Franciso_S3.txt
UK_Glouchester_S4.txt
Argentina_Buenos_Aires_S7.txt
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我吗,最好使用mv命令吗?谢谢。

Raf*_*ffa 8

#!/bin/bash

for f in *.txt; do # Work on files with ".txt" extension in the current working directory assigning their names one at a time(for each loop run) to the variable "$f"
    IFS=', ' read -r -a array <<< "$f" # Split filename into parts/elements by "," and " " and read the elements into an array
    f1=$(IFS="_$IFS"; printf "${array[*]}"; IFS="${IFS:1}") # Set the new filename in the variable "$f1" by printing array elements and adding "_" inbetween.
    echo mv -n -- "$f" "$f1" # Renaming dry-run(simulation) ... Remove "echo" when satisfied with output to do the actual renaming.
done
Run Code Online (Sandbox Code Playgroud)

或者

#!/bin/bash

shopt -s extglob # Turn on "extglob"

for f in *.txt; do # Work on files with ".txt" extention in the current working directory assigning their namese one at a time(for each loop run) to the fariable "$f"
    echo mv -n -- "$f" "${f//+([, ])/_}" # Renaming dry-run(simulation) ... Remove "echo" when satisfied with output to do the actual renaming.
done
Run Code Online (Sandbox Code Playgroud)


Pab*_*chi 8

使用 Perl 很简单rename在此处此处提到;不要与其他重命名混淆):

rename 's/,? /_/g' *.txt     # Or rename 's/(, | )/_/g' *.txt
Run Code Online (Sandbox Code Playgroud)

可以与-vn: --verbose(打印已成功重命名的文件的名称) 和--nono(打印要重命名的文件的名称,但不要重命名。

  • 可能值得一提的是,添加“-vn”将允许人们在不执行重命名的情况下查看重命名。 (2认同)