basename: What I had in mind

A while back, when I said I dumped coreutils back into The List because I thought there were still a few useful programs in there, I was thinking mostly of basename. So I’m kind of glad that shuf spat it out today.

I use basename a lot, although I can’t pin down any regular case that you might identify with. Here’s one that comes to mind though: Making sure the index page in my local wiki has all the programs included in the directory.

Occasionally I get sloppy and lose a title, or worse, have a file in the directory that doesn’t have a corresponding link in the index. That’s a problem because I can go months without knowing there’s an additional program in there.

I solve that by periodically dumping all the names of the files into an empty wiki page, and check links manually. vimwiki makes that fairly easy, since one press of the enter key will create a link, and the next will follow it. If the page is blank, it was a missing file, but if the file is there I can check that against my old list.

All this is terribly uninteresting. Let’s get to the good part. I use find to pluck out all the files from within /home/kmandla/vimwiki/ :

find . -type f

find naturally shows a preceding ./ for each file. I could fix that by adding -printf "%f\n" at the end, but vimwiki tacks .wiki on the end of each file, so I’d end up using basename anyway to get rid of that.

Ergo,

find . -type f -exec basename "{}" .wiki \;

In that case, basename trims off the leading path, and then the suffix .wiki from whatever it is given. The next step, which I won’t bother showing, is to dump all that into a separate file.

basename can cut off whatever you like from the end of a file, provided you predict it correctly. It’s a good way to trim file extensions, if you know what they are (if you don’t, you should be thinking about cut).

I have other uses for basename, and I can’t think of them right now. Perhaps in the future I’ll come back and add them on here, just for future reference. 🙂