Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question

3 Answers 3

up vote 9 down vote accepted

Using standard POSIX parameter expansion:

for f in *.shp; do printf '%s\n' "${f%.shp}_poly.shp"; done
share|improve this answer
    
Awesome that is exactly what I needed. –  Sam007 Nov 26 '12 at 21:05
    
Might be better with an explanation how it works. The Doug answer is pretty easy, on the other hand. –  Sarge Borsch Jun 23 at 12:41
    
@SargeBorsch What do you need explained? My answer, the snippet in the question, and Doug's answer are only differ by a few characters, and Doug's answer explains even less than mine so I don't know what it is you want. If you just compare the difference in the two outputs in the question it should be trivially easy to figure out what they do. I can explain why my answer is preferable to Doug's. 1. I use printf with a format string instead of the less portable echo. 2. I use parameter expansion which is more efficient than calling an external binary (basename) for such a simple task. –  jw013 Jun 23 at 14:43

Use this:

for file in *.shp; do echo $(basename $file .shp)_poly.shp; done
share|improve this answer
3  
Using basename is slower and less efficient than letting the shell do the work by itself. This may be noticeable for very large numbers of files. –  jw013 Nov 26 '12 at 21:14

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.