2

I have >2000 files which are named like

123-FILENAME_TEXT_M101K_20150929.CSV

where 123 can be any three or four-digit number. The files are all within the same directory. I would like a script that removes the prefixing number and the dash. (i.e. the leading 123- should be removed from the example name)

I have tried mv **-FILENAME* FILENAME*. rename is not an available function

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
Kim
  • 23
  • 5
  • This question is very similar to [Remove prefixes from filenames](https://unix.stackexchange.com/q/45212). Maybe even a duplicate? – Henke Feb 07 '22 at 14:11

2 Answers2

4

You could try something like this, it will remove everything before the first -

for file in *-*.CSV
do
   newName="${file#*-}"
   mv -- "${file}" "${newName}"
done
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
mmoisse
  • 60
  • 5
  • 1
    The assignment is actually [one of the few places](https://unix.stackexchange.com/q/68694/170373) that don't need the quotes (unless you use an unquoted `$*` there in Bash; It's had a bunch of bugs with that) – ilkkachu Jan 31 '18 at 14:42
  • Quotes are indeed a source of bug, but I didn't know that it was not needed on assignment. Tx – mmoisse Jan 31 '18 at 14:45
  • 1
    Quotes won't harm anyway. To clarify @ilkkachu's comment, in the case of bash's `var=$*`, it's the absence of quotes that cause problems. – Stéphane Chazelas Jan 31 '18 at 15:12
  • Sorry I am a bit stuck, I have tried running this as a shell script but getting bad substitution - any ideas where I am going wrong? – Kim Jan 31 '18 at 15:41
  • Solved, I was running as a .sh rather than .bash, even thou in my script I had #!/bin/bash. Any all work now tysm – Kim Jan 31 '18 at 15:56
2

I have tried by using combination of sed,awk and find . Tested and working fine

find . -type f -iname "*.CSV"| sed "s/^\.\///g"| sed -n '/^[0-9]\{4\}/p' | awk   -F "-" '{print "mv" " " $0 " " $2}'| sh
Praveen Kumar BS
  • 5,139
  • 2
  • 9
  • 14