Several options:
awk '
function basename(file) {
sub(".*/", "", file)
return file
}
{print FILENAME, basename(FILENAME)}' /path/to/file
Or:
awk '
function basename(file, a, n) {
n = split(file, a, "/")
return a[n]
}
{print FILENAME, basename(FILENAME)}' /path/to/file
Note that those implementations of basename
should work for the common cases, but not in corner cases like basename /path/to/x///
where they return the empty string instead of x
or /
where they return the empty string instead of /
, though for regular files, that should not happen.
The first one will not work properly if the file paths (up to the last /
) contain sequences of bytes that don't form valid characters in the current locale (typically this kind of thing happens in UTF-8 locales with filenames encoded in some 8 bit single byte character set). You can work around that by fixing the locale to C where every sequence of byte form valid characters.
n = split(FILENAME, a, "/"); basename=a[n];
. Don't usesub
as that will actually change theFILENAME
variable (which is a non-issue with the function since awk uses call by value). – shiri Jan 07 '18 at 09:28