Extract directory, filename, and extension in Bash shell

https://stackoverflow.com/questions/965053/extract-filename-and-extension-in-bash

$> FILE_PATH="dir/example.tar.gz"
$> FILE="example.tar.gz"

$> dirname $FILE_PATH
dir

$> dirname $FILE
.

$> basename $FILE_PATH
example.tar.gz

$> basename $FILE
example.tar.gz

# -------------------------------
# dir/example.tar(.gz) :
$> echo "${FILE_PATH%.*}"
dir/example.tar

# dir/example(.tar(.gz)) :
$> echo "${FILE_PATH%%.*}"
dir/example


# example.tar(.gz) :
$> echo "${FILE%.*}"
example.tar

# example(.tar(.gz)) :
$> echo "${FILE%%.*}"
example

# ---------------------------------------

# (dir/example.)tar.gz :
$> echo "${FILE_PATH#*.}"
tar.gz

# ((dir/example.)tar.)gz :
$> echo "${FILE_PATH##*.}"
gz

# (example.)tar.gz :
$> echo "${FILE#*.}"
tar.gz

# ((example.)tar.)gz :
$> echo "${FILE##*.}"
gz

Extract file basename and extension

$> basename $FILE_PATH
example.tar.gz

$> basename $FILE_PATH | (read NAME; echo $NAME)
example.tar.gz

# basename cropped extension :
$> basename $FILE_PATH | (read NAME; echo ${NAME%.*})
example.tar

$> basename $FILE_PATH | (read NAME; echo ${NAME%%.*})
example


# basename extension :
$> basename $FILE_PATH | (read NAME; echo ${NAME#*.})
tar.gz

$> basename $FILE_PATH | (read NAME; echo ${NAME##*.})
gz

Example

$> FILE_PATH="node_modules/example/index.js"

$> echo $FILE_PATH
node_modules/example/index.js

$> echo "${FILE_PATH%.*}"
node_modules/example/index

$> echo "${FILE_PATH#*.}"
js

# variable=$(shell command)
$> minFile=$(echo "${FILE_PATH%.*}.min.${FILE_PATH#*.}")

$ echo $minFile
node_modules/example/index.min.js

Execute a Unix Shell Command with Node.js

// <http://nodejs.org/api.html#_child_processes>

var sys = require('sys')
var exec = require('child_process').exec;
var child;

// executes `pwd`
child = exec("pwd", function (error, stdout, stderr) {
sys.print('stdout: ' + stdout);
sys.print('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});

// or more concisely
var sys = require('sys')
var exec = require('child_process').exec;

function puts(error, stdout, stderr) { sys.puts(stdout) }

exec("ls -la", puts);

Leave a Reply