Substring Function

I have a file in which there are other file path and names

/home/data/abc.txt
/home/data/sdf.txt
/home/data/sdg.txt

how can I get the file names i.e. abc.txt sdf.txt sdg.txt

I searched the forum for sed command but it was confusing to me

Try:

perl -pe 's#.*/##' file

Also:

 while read -r a; do basename "$a"; done <file

Or, if you like sed:

sed 's|.*/||' <file

--
Bye

while read line
do
file=`basename $line`
echo $file
done < yourfilename

assuming you need all file names irrespective of extension type.

You don't need backticks to do that :slight_smile:

OLDIFS="$IFS"
IFS="/"

while read LINE
do
        set -- "$LINE"
        shift $(( $#-1 ))
        echo "Got $1"
done

IFS="$OLDIFS"

Shorter:

while read line
do
 echo "Got ${line##*/}"
done < file

Here is one more way...probably quickest :slight_smile:

 awk -F"/" '{print $NF}' file.txt 

We can't forget: egrep -o "[^/]+$" file :slight_smile:
--
Bye

Try like...

 awk -F'/' '{print $4}' test.txt

Hi Elixir/Bartus,

Can you please explain the use of HASH # here in code. How it works?

See the Advanced Bash Scripting Guide (String Operations). Most of those will work fine in BASH or KSH, and a few other shells as well.