adding text to filename before extension

I would like to add text to the end of filename but before the extension. Right now I am trying,

for f in *.shp; do echo $f_poly; done

the output is,

Quercus_acutifolia.shp_poly
Quercus_agrifolia.shp_poly
Quercus_corrugata.shp_poly
Quercus_cortesii.shp_poly
Quercus_costaricensis.shp_poly
Quercus_havardii.shp_poly
Quercus_hemisphaerica.shp_poly
Quercus_kelloggii.shp_poly
Quercus_knoblochii.shp_poly
Quercus_laceyi.shp_poly

I want it to be,

Quercus_acutifolia_poly.shp
Quercus_agrifolia_poly.shp
Quercus_corrugata_poly.shp
Quercus_cortesii_poly.shp
Quercus_costaricensis_poly.shp
Quercus_havardii_poly.shp
Quercus_hemisphaerica_poly.shp
Quercus_kelloggii_poly.shp
Quercus_knoblochii_poly.shp
Quercus_laceyi_poly.shp
Asked By: Sam007

||

Using standard POSIX parameter expansion:

for f in *.shp; do printf '%sn' "${f%.shp}_poly.shp"; done
Answered By: jw013

Use this:

for file in *.shp; do echo $(basename $file .shp)_poly.shp; done
Answered By: doneal24

Sometimes there is a tool called “rename” installed.

rename 's/.shp$/_poly.shp/' *shp

It might not be portable but it is easy to use.

Answered By: Chad Clark

If they are in different locations then run :-

for i in ` find /root/test/ -name "*.shp" ` ;
do
  mv $i ` echo $i | sed 's/.shp$/_poly.shp/g' ` ;
done
Answered By: Shankey Ravi

This worked better for me:

for f in *; do NEW=${f%.webm}_2016.webm; mv ${f} "${NEW}"; done

Answered By: Vinnie James

As the question is for bash there is no need for external utilities, since you can use bash regexps:

for f in *.shp
do
    mv -v "${f}" "${f%.*}_MYSUFFIX.${f##*.}"
done

❗️Warning: for f in *.ext is not reliable as it will break on file names containing spaces, quotes or other reserved characters. A failsafe approach would be using something like find . -iname '*.shp' -exec sh -c 'mv -v "${1}" "${1%.*}_MYSUFFIX.${f##*.}"' _ {} ;. If you don’t need recursive traversal then add -maxdepth 1

Answered By: ccpizza
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.