Reputation: 129
When I use the following code, I get output such as:
/home/pony/IOSO/test/A
/home/pony/IOSO/test/B
FILE=last.cfg
DIR=$(realpath "$2") #or something else
grep $DIR $FILE | awk '{ print $2 }' | sort | uniq # | basename does not work
How do I make my pipe work with basename or something like this:
$ s=/the/path/foo.txt
$ echo ${s##*/}
foo.txt
Upvotes: 2
Views: 1021
Reputation: 26667
You can do this using awk
so that you can avoid the unecessary usage of grep
awk
and sed
sequance
The correct method can be
awk -v dir="$DIR" -F"/" '$0 ~ dir{print $NF}'
Test
$ DIR="/home/pony/IOSO/test"
$ cat input
/home/pony/IOSO/test/A
/home/pony/IOSO/test/B
/home/test/test
$ awk -v dir="$DIR" -F"/" '$0 ~ dir{print $NF}' input
A
B
What it does
-v dir="$DIR"
creates an awk
variable with the value of shell variable DIR
-F"/"
set the field delimiter as the /
. This is done as in input file the directories are separated by /
and we need to get the last field, filename.
'$0 ~ dir
checks for each input line if it matches the pattern in variable dir
print $NF
print the last field, here the the filename. NF
stands for number of fields.
Upvotes: 1
Reputation: 174796
Just pass the uniq
command's output to a sed command like below to remove all the characters upto the last /
symbol.
grep $DIR $FILE | awk '{ print $2 }' | sort | uniq | sed 's~.*/~~'
Upvotes: 1