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.

Possible Duplicate:
Best way to remove file extension from a string?
How to rename multiple files by removing the extension?

I have a metric boatload of .txt files I'd like to load into a database.

The tables have the same name as the .txt files, but without the extension.

So I'd like to execute the command

for f in *.txt; do mysql -u root -p -e "LOAD DATA LOCAL INFILE '$f' INTO TABLE $f" -D rn4; done

However, the last $f is giving me headaches as I want it to only use the name, not the extension.

So for the file piRNA.txt the command would look like

mysql -u root -p -e "LOAD DATA LOCAL INFILE 'piRNA.txt' INTO TABLE piRNA" -D rn4

How do I do this?

To make the answer useful for others, please do not just give me the command, but please write a line or two about how to extract the name in the general case.

share|improve this question
    
Not a duplicate, but it seems to contain the answer. Did not know about the 'basename' command. Will keep this question as other people wondering about the same thing are unlikely to find that thread by any reasonable search. –  The Unfun Cat Nov 26 '12 at 8:13
1  
Parameter expansion would work bettter in your case, IMO. Also, it's a duplicate if the answer is the same, irrespective of how you ask the question ;) –  jasonwryan Nov 26 '12 at 8:20
add comment

marked as duplicate by jasonwryan, sr_, Renan, Mat, Gilles Nov 28 '12 at 23:50

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

up vote 4 down vote accepted

You can do it like this in a shell script:

f=piRNA.txt
g=${f%.txt}

Executing

 echo $f $g

yields following output:

piRNA.txt piRNA

With that % syntax you remove a matching suffix patttern. The suffix pattern in the example is .txt and f is the variable it is removed from. Note that a pattern may also contain wildcards (cf. e.g. the bash manual for details).

As always, in case your filenames may contain spaces you have to put the references of variables into double quotes (e.g. "$f" etc.).

share|improve this answer
    
20 seconds before you ;) But I'll accept yours if you explain what that command does. Pretty please? –  The Unfun Cat Nov 26 '12 at 8:23
    
@TheUnfunCat, no problem, is this explanation sufficient? –  maxschlepzig Nov 26 '12 at 8:31
add comment

Try this you dumdum:

for f in *.txt; do echo ${f%.*};done

(Have no idea why this works.)

share|improve this answer
add comment

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