Sandra Schlichting
Sandra Schlichting

Reputation: 25986

Remove fixed filename extension in one-liner

When I do

ruby -e 'print "file: #{ARGF.filename}"' test1.adoc

it prints test1.adoc, but what I am looking for is to have the extension removed, so I just get test1. If do

$ touch test1.adoc
$ ruby -e 'print "file: #{ARGF.filename}.sub('.adoc','')"' test1.adoc
Traceback (most recent call last):
    1: from -e:1:in `<main>'
-e:1:in `filename': No such file or directory @ rb_sysopen - test1.adoc (Errno::ENOENT)

Using pop is temping to get a generic solution, but that seams harder going down that path...

Question

Can anyone figure out howto remove .adoc in my one-liner?

Upvotes: 2

Views: 58

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use

ruby -e 'print "file: #{File.basename(ARGF.filename, '"'.*'"')}"' test.adoc

The File.basename with the second argument set to .* returns file name without any extensions, but you need to quote the single quotes correctly in order to keep syntax right.

In '"'.*'"', the first ' closes the currently open ' before print, then "'.*'" adds '.*' to the line of code, then ' re-starts the code line to be closed with the trailing '.

Upvotes: 1

Schwern
Schwern

Reputation: 164679

Use File.basename to remove the extension, and the rest of the file path.

puts File.basename('test1.adoc', '.*')  # test1
puts File.basename('/foo/bar/test1.adoc', '.*')  # test1

Upvotes: 2

Related Questions