How to get the last field of a string using cut command in bash linux ?

Today we will see an interesting article how to get the last field of a string using cut command in linux.

Suppose you are searching for files and want to cut the last field after “/” in below output.

I. Requirement:- Get only filename from find command output.

[ngeuser@ngelinux001 test]$ find . -type f -print
./test5/c
./test5/test2/test3/d
./b
./test6/99
./a4

 

II. Solution
We have a command called “rev” available to reverse the output and hence we can get the last field using below command.

[ngeuser@ngelinux001 test]$ find . -type f -print | rev | cut -d '/' -f1 | rev
c
d
b
99
a4

Here we have revered the output of first command and then cut off the first field and then reversed the output back.

The last rev is sometimes useful as sometimes the filenames are also reversed.
So make sure to use that as well.

 

III. Getting the directory path except filename in find command output.

Similarly if you want to get the directory path except the filename, we can get that using below command.

[ngeuser@ngelinux001 test]$  find . -type f -print  | rev | cut -d '/' -f 2- | rev
./test5
./test5/test2/test3
.
./test6
.
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments