我的文件格式为
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命令吗?谢谢。
#!/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)