6

I have few files in the following directory: /var/lib/jenkins/bin/

-rwxr-xr-x. 1 root root 4430846 Apr 27 09:45 01-DSP-04.12_03_crc.bin
-rwxr-xr-x. 1 root root 1659036 Apr 27 09:45 01-FL4-04.12_02-crc.bin
-rwxr-xr-x. 1 root root 1659036 Apr 27 09:45 01-FL8-04.12_02-crc.bin
-rwxr-xr-x. 1 root root 1659036 Apr 27 09:46 01-FPGA-04.12_02-crc.bin
-rwxr-xr-x. 1 root root  524328 Apr 27 09:46 01-MMI-04.11_05-crc.bin
-rwxr-xr-x. 1 root root   27692 Apr 27 09:46 01-PIC-04.11_06-crc.bin

Also, I have a script that does some work at /var/lib/jenkins/scripts/my_script.sh.

I want to remove the leading "01-" from the file names from this script. Is there any good way of doing this?

I tried the solution from https://stackoverflow.com/questions/28305134/remove-first-n-character-from-bunch-of-file-names-with-cut but do not work for me.

I get output like this:

Command

$ for file in /var/lib/jenkins/bin/*; do echo mv $file `echo $file | cut -c4-`; done

Output

mv /var/lib/jenkins/bin/01-DSP-04.12_03_crc.bin r/lib/jenkins/bin/01-DSP-04.12_03_crc.bin
mv /var/lib/jenkins/bin/test.sh r/lib/jenkins/bin/test.sh

As you can see it removes first 3 character which is directory name, not file name. I want to remove 3 character after 21 character from file name.

Any better way to do this?

  • You can use the string manipulation from bash in tandem with for loop as: for i in 01-?*; do mv -v "$i" "${i:3}"; done –  Apr 27 '17 at 15:10

1 Answers1

8

The problem is that you are using the full path, so that includes the directory. The simplest workaround is to first cd into the target directory and then run the for loop:

cd /var/lib/jenkins/bin
for file in *; do echo mv "$file" "$(echo "$file" | cut -c4-)"; done

Or, using the shell's own string manipulation abilities:

cd /var/lib/jenkins/bin
for file in *; do echo mv "$file" "${file#????}"; done

Alternatively, if you have perl-rename (called rename on Debian-based systems, perl-rename on others) , you can do:

rename -n 's|.*/...||' /var/lib/jenkins/bin/*

Once you've made sure that works, remove the -n to make it actually rename.


However, as Sundeep pointed out in the comments, if you only want to remove 01-, then remove that specifically:

rename -n 's|.*/01-||' /var/lib/jenkins/bin/*
terdon
  • 242,166
  • 1
    typos... extra " in first command... should be 3 dots for rename... imo, using echo mv "$file" "${file#01-}" is safer.. deletes only if 01- is present at start... and is easy to change instead of dealing with number of characters.. (assuming bash) – Sundeep Apr 27 '17 at 11:21
  • 1
    @Sundeep eeek! Wow, I was really not paying attention. Thanks! – terdon Apr 27 '17 at 11:24
  • And you could still do "${file#???}" to remove any first three chars without running cut – ilkkachu Apr 27 '17 at 12:10
  • @ilkkachu OK, done. – terdon Apr 27 '17 at 12:53