'How to create a FileNameAppender
Im quite new shell/bash for linux. Im trying to create a script which changes all files within a specific folder. The script should ask me following:
- Do I want a Prefix or Suffix
- Ask me to enter the Affix(Prefix/Suffix) word I want.
- Ask me if I want to add a counter (so my affix word + a counter) And then change all filenames according to the parameters selected above.
Does anyone have a part of this already or can give me some tipps? I code with java but having trouble with the syntax of bash.
Solution 1:[1]
i think it's better to use arguments like -p {value} for prefix and -s {value} for sufix and -c {counter_value}, for this you can use getopts.
And to list the files in specified folder you can define the argument -f {path_to_folder} and pass this value to find command (i have a project on github that's use this https://github.com/MarciovsRocha/todoList/blob/master/teste.sh)
Should be something like that:
while getopts 'f:c:s:p:' flag; do
case "${flag}" in
p) prefix="${OPTARG}" ;;
s) sufix="${OPTARG}" ;;
c) counter="{$OPTARG}" ;;
f) path="${OPTARG}" ;;
*)
echo "Invalid parameter."
exit 1
;;
esac
done
# generates an array with all files in specified folder
mapfile files <<< "$(find "$path" -maxdepth 1 ! -type d)"
# for file in array changes the name with mv
for file in files "${files[@]}"; do
file="$(tr -d '\n' <<< "$file")" # this will format the string removing the newline at the end
mv "${path}/${file}" "${path}/${prefix}${file}${sufix}${counter}" this line will
done
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcio Rocha |
