Extract filename from a given string

I want to extract the filename from a string.

This is how I have the rawdata ina file

/home/sid/ftp/testing/abc.txt
/home/sid/ftp/tested/testing/def.txt
/home/sid/sftp/date/misc/hij.txt

i want a script which would provide me an output like this

Directory Filename
/home/sid/ftp/ abc.txt
/home/sid/ftp/tested/testing def.txt
/home/sid/sftp/date/misc hij.txt

All help appreciated.

Actually, you can help yourself, if you want. Look at this example:

file_path="/home/sid/ftp/tested/testing/def.txt"

echo ${file_path%/*} # this will display the directory path
/home/sid/ftp/tested/testing

echo ${file_path##*/} # this will display the file name without path
def.txt

Set up a loop with each absolute path and you have your script.

When I put it in a loop it said bad substitution

This is the code

for i in `cat filename`
do
echo ${$i%/*} echo ${$i##*/}
done

It gave this error

bash: echo ${file_path%/*}:bad substitution

That was a good try, but it has a couple syntax errors.
Remove the red `$' and add the red `;'

However, that would display path and file in two different lines.
Modify as:

for i in `cat filename`
do
    printf "%s %s\n" ${i%/*} ${i##*/}
done
1 Like

Brilliant Aia! It worked, thanks

You can also use basename and the dirname to get the output
basename /tmp/abc.txt will give abc.txt
dirname /tmp/abc.txt will give /tmp

1 Like

That is almost almost always the wrong way ro read the contents of a file. Not only is cat unnecssary but it will break your script if any lines contain whitespace or other pathological characters. It should be:

while read i
do
    printf "%s %s\n" "${i%/*}" "${i##*/}" ## note the quotes!
done < "$filename"
1 Like

also please use "basename" command it extract the file names

Do not use basename . It is an external command that is an order of magnitude slower than using the shell's parameter expansion.

2 Likes

Thank you for making it clear.

Thanks cfajohnson. I didnt realize those scenarios with cat.