0

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

Andy K
  • 4,944
  • 10
  • 53
  • 82
  • So you want to rename those files based on this condition? – fedorqui Mar 24 '14 at 15:03
  • Yes , Fedorqui. If the string `codeGroupe` does not exist in the filename. – Andy K Mar 24 '14 at 15:06
  • `-q` silences the output, so you can simply say `if grep -q ...`; then`, and let the exit status of `grep` control the `if` statement without having to actually see the output. – chepner Mar 24 '14 at 15:07
  • I want to see the output actually, Chepner. – Andy K Mar 24 '14 at 15:08
  • I don't understand how you get from `idbank.xls` to `xxxcodeGroupea1111.xls`. Where did the `xxx` come from? Where did the `idbank` go? Also, it's not possible for a single directory to have multiple files all named `idbank.xls`. – ruakh Mar 24 '14 at 15:13
  • Ruakh, I meant `idbankxxxcodeGroupea1111.xls` – Andy K Mar 24 '14 at 15:18

1 Answers1

1

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
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598