Andy K
Andy K

Reputation: 5054

append string to file name when string is missing

I'm trying to append a string into a file name , each time that string is missing.

Example :

I have

idbank.xls
idbank.xls
idbank.xls

I'm looking for the string

codegroup

As the string does not exist, I'm appending it to the file name before the extension. The required output will be

idbankxxxcodeGroupea1111.xls
idbankxxxcodeGroupea1111.xls
idbankxxxcodeGroupea1111.xls

I made this script (see below) but it is not working properly

for file in idbank*.xls; do
 if $(ls | grep -v 'codeGroupe' $file); then
  printf '%s\n' "${f%.xls}codeGroupea1111.xls"
 fi; done

The grep -v is to check if the string is here or not. I read on a different post that you can use the option -q but in checking the man , it says it is for silent...

Any suggestions would be helpful.

Best

Upvotes: 0

Views: 119

Answers (1)

fedorqui
fedorqui

Reputation: 290155

This can make it:

for file in idbank*xls
do
  [[ $file != *codegroup* ]] && mv $file ${file%.*}codegroup.${file##*.}
done
  • The for file is what you are already using.
  • [[ $file != *codegroup* ]] checks if the file name contains codegroup or not.
  • If not, mv $file ${var%.*}codegroup.${var##*.} is performed: it renames the file by moving it to filename_without_extension + codgroup + extension (further reference in Extract filename and extension in bash).

Note

[[ $file != *codegroup* ]] && mv $file ${file%.*}codegroup.${file##*.}

Is the same as:

if [[ $file != *codegroup* ]]; then
  mv $file ${file%.*}codegroup.${file##*.}
fi

Upvotes: 1

Related Questions