The macOS Terminal is simply an interface to an interactive program called a shell. The default shell's name is bash
.
What you are looking for is known as a shell script, or a bash script, to rename files.
The questions you referenced have the answer. To reiterate:
cd directory_with_the_files
for file in *.fq; do
mv -vn "${file}" "${file%_*}.fq"
done
You can type this all in at the command line, or place it into a file and execute it with:
bash file_containing_the_commands
This will go through all .fq
files in the current directory, renaming them to what you want. The -v
option to mv
simply means to print the rename as it happens (useful to know that it's doing something), and the -n
flag means don't accidentally overwrite any files (in case you type something in wrong or come across duplicate numbers).
All the magic is happening in the ${file%_*}.fq
, which says
"remove everything after the first _
and add the .fq
back". This is known as a "shell parameter expansion," which you can read more about in the Bash Reference Manual. It's somewhat obtusely worded, but here is the relevant bit to this particular use case:
${parameter%word}
The word is expanded to produce a
pattern just as in filename expansion. If the pattern matches a
trailing portion of the expanded value of parameter, then the result
of the expansion is the value of parameter with the shortest matching
pattern (the '%' case) deleted.