This can be done in many ways ... I'll list three ways below for example.
First way
Using mmv
:
mmv -n -- '*_*_*_*_*.fastq' '#1_#4.fastq'
'*_*_*_*_*.fastq'
will work on all files with an extension of .fastq
in the current working directory splitting the file name into parts(where *
is) by the specified delimiter i.e. _
... These parts are then called by number #
(the first one being #1
) to form the new filename i.e. '#1_#4.fastq'
... The -n
option is for dry-run(simulation but no actual renaming is done) ... Remove -n
when satisfied with the output to do the actual renaming.
Second way
Using rename
:
rename -n 's/^([^.]+)\_([^.]+)\_([^.]+)\_([^.]+)\_([^.]+)\.fastq$/$1_$4.fastq/' *.fastq
Please see this answer(The explanation part) for explanation on hwo it works and this link for regular expressions break down ... The -n
option is for dry-run(simulation but no actual renaming is done) ... Remove -n
when satisfied with the output to do the actual renaming.
Third way
Using mv
with bash arrays in a bash for loop in a bash shell script file:
#!/bin/bash
for f in *.fastq; do # Work on files with ".fastq" extention in the current working directory assigning their namese one at a time(for each loop run) to the fariable "$f"
IFS='.' read -r -a array <<< "$f" # Split filename into parts/elements by "" and "." and read the elements into an array
f1="${array[0]}${array[3]}.${array[5]}" # Set the new filename in the variable "$f1" by sellecting certain array elements and adding back "" and "."
echo mv -- "$f" "$f1" # Renaming dry-run(simulation) ... Remove "echo" when satisfied with output to do the actual renaming.
done
or in a bash command string:
bash -c `for f in *.fastq; do IFS='_.' read -r -a array <<< "$f"; f1="${array[0]}_${array[3]}.${array[5]}"; echo mv -- "$f" "$f1"; done`
rename -e 's/^[^_]*_//' -e 's/_R[12]_001.fastq$//' *
– FedKad Jun 29 '22 at 15:22mmv
for this - see similar answer at change all file names (prefix to postfix) – steeldriver Jun 29 '22 at 16:19