Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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.

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
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
up vote 6 down vote accepted

You can do it like this in a shell script:



 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

Try this:

for f in *.txt; do echo ${f%.*};done
  • Using pattern matching *.txt to match all files end with .txt
  • ${f%.*} is shell syntax for Parameter Expansion, remove the smallest suffix matched pattern in $f. Here we remove the extension part .txt.
share|improve this answer

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