2

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.

  • 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 08: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 08:20

2 Answers2

10

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.).

maxschlepzig
  • 57,532
4

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.