[英]Bash Script - Replace Last Comma In Folder Names with an &
I need help writing a Bash script.我需要帮助编写 Bash 脚本。 I want it to go through a folder and rename all sub-folders to replace the LAST comma with an ampersand.
我希望它通过文件夹 go 并重命名所有子文件夹以用&符号替换 LAST 逗号。
for dir in /home/john/Documents/TEST/*;
do
# ***This is the part I can't figure out***
done
Say the folder is '1234 John, James, Jack'
- I want it to become '1234 John, James & Jack'
假设文件夹是
'1234 John, James, Jack'
- 我希望它变成'1234 John, James & Jack'
This is a suitable job for a parameter expansion ;这是一个适合参数扩展的工作; techniques using them for this and similar purposes are also covered within BashFAQ #100 .
BashFAQ #100中还介绍了将它们用于此目的和类似目的的技术。
for f in /home/john/Documents/TEST/*,*/; do # final / means we match only directories
f=${f%/} # remove the last /
front=${f%,*} # front is everything before the last comma
back=${f##*,} # back is everything after the last comma
mv -- "$f" "${front}&${back}"
done
See this demonstrated at the online REPL at https://ideone.com/XcY4rw请参阅https://ideone.com/XcY4rw的在线 REPL 演示
for dir in /home/john/Documents/TEST/*,*/;
do
newdir=$(echo "${dir}" | sed 's/\(.*\),/\1\&/')
mv "${dir}" "${newdir}"
done
You can just use use sed
to replace the last comma in dir name by &.您可以使用
sed
将目录名称中的最后一个逗号替换为 &。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.