How do I get the last field of Windows filenames?

Ubuntu Version:
24.04

Desktop Environment (if applicable):
GNOME

Problem Description:
I have a file with the names of files I need to delete. Their format is:
C:\msts\Trains\Consists\#MT_DB_NSE_315.con
C:\msts\Trains\Consists\#MT_DB_NSE_315x2.con
C:\msts\Trains\Consists\#MT_MT 86246 IC Up Rake.con

What I need is the bare filename, without the path. E.g., from
C:\msts\Trains\Consists\#MT_DB_NSE_315.con I want to keep only #MT_DB_NSE_315.con

I thought “awk -F\ ‘{ print $NF }’” should do it, but it prints the whole line. The problem seems to be with the backslash. I’ve also tried it escaped (with the backslash) and it doesn’t help.

What am I doing wrong?

Try this (notice the \ is between ' '):

awk -F '\' '{print $NF}'

1 Like

That did it after I 'sudo’ed the command. Don’t know why I’m always forgetting ‘sudo’.

So, the solution is: $ sudo awk -F’' ‘{ print $NF}’ Del_Con-File.txt

$ cat list | cut -d"\\" -f 5
#MT_DB_NSE_315.con
#MT_DB_NSE_315x2.con
#MT_MT 86246 IC Up Rake.con
1 Like
$ cat list | sed 's/^.*\\//g'
#MT_DB_NSE_315.con
#MT_DB_NSE_315x2.con
#MT_MT 86246 IC Up Rake.con

A million roads lead to rome :wink:

1 Like

It wasn’t really made for backslash handling… (In fact it doesn’t what it is supposed to do (return the last bit of a path) in your example due to the backslashes)

Jeez, I clearly haven’t had enough coffee this morning. What was I thinking with my (now deleted) useless reply :smiley:

1 Like

Luckily I’ve got Windows running in a VM, so I can transfer the files back to Ubuntu for processing with the Unix tools and then transfer them back to use. The backslashes really can be a problem, because I used to run Cygwin, which uses the forward slashes.

1 Like

This topic was automatically closed after 30 days. New replies are no longer allowed.