Assuming these are names of files on disk that you want to rename, not strings stored in a variable or in a text file. You may use a simple shell loop:
for name in *.fastq; do
newname=${name#*_*_*_}
printf 'Would move "%s" to "%s"\n' "$name" "$newname"
# mv -i -- "$name" "$newname"
done
This loops over all names that matches the pattern *.fastq
in the current directory (you may want to be more specific with this pattern by e.g. changing it to IDNR*.fastq
). For each filename, it constructs a new name by removing the prefix that matches the filename globbing pattern *_*_*_
. This is done using a standard parameter expansion.
For safety, the mv
is commented out. You should run the code once to see that it does the right thing before enabling the mv
.
Using one of the various rename
utilities (the one based on Perl's File::Rename
module; there are a number of different ones, see "What's with all the renames: prename, rename, file-rename?"):
rename -n -v 's/.*?_.*?_.*?_//' -- *.fastq
or shorter,
rename -n -v 's/(.*?_){3}//' -- *.fastq
This more or less does the same thing as the shell code above, but using a Perl substitution. The substitution removes the initial bits of the filename string by matching the three substrings between the underscores using a non-greedy .*
match. Remove the -n
option when you are confident that it does the right thing.
rename
command, if you can get it in whichever OS you're using – muru Mar 19 '20 at 06:59