-1

Let's suppose I have a bash script named bash.sh in a folder /home/test/ and within this folder I also have 5 more files named as: file_1a.nc file_1b.nc file_2a.nc file_6a.nc file_6b.nc.

I would like to copy bash.sh 5 times and the new copies need to have the same name as the .nc files, as follows:

file_1a_bash.sh file_1b_bash.sh file_2a_bash.sh file_6a_bash.sh file_6b_bash.sh

Any suggestion? Thanks

aaaaa
  • 149
  • 2
  • 18
  • 44

2 Answers2

2

This is just a simple case of bash Parameter Expansion processing.

for f in file_*.nc; do cp bash.sh "${f%.nc}_bash.sh"; done
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
  • The idea seems good to me, but [Shellcheck](https://www.shellcheck.net/) identifies missing quotes in the code. – pjh Jan 30 '20 at 16:06
  • @pjh missing quotes wouldn't be a problem in this particular case since samples in the OP do not contain spaces or any other meta-chars. Please don't make shellcheck another cargo cult – oguz ismail Jan 30 '20 at 17:24
  • 1
    It is nonetheless a good habit to always put quotes unless there is a sound and explicit reason not to do so. I just wanted to keep the example minimal and simplistic to accentuate the point, but now that's been done, I'll add them as good form. – Paul Hodges Jan 30 '20 at 19:57
-2

You can apply this earlier answer to your case

find /home/test/ -type f -name '*.nc' | while read f; do 
mv "$f" "${f%.nc}_bash.sh"; 

You can also use ls -1 when you are in /home/test/ instead of find;

for f in `ls -1 file_*` ; do 
cp ${f} "${f%.nc}"_bash.sh; 
done
Tom
  • 1
  • 2
    I would do for f in file_* ; do cp "${f}" "${f%.nc}"_bash.sh; done It's not convenient to use ls to loop files, use glob notation instead. And always protect your vars double quoting them. You can have a check on https://www.shellcheck.net/ – Francesco Gasparetto Jan 30 '20 at 14:20
  • 1
    Neither find nor ls is required here – oguz ismail Jan 30 '20 at 15:04