Retrieve directory path from full file path through sh

Hi,

I have a file abcd.txt which has contents in the form of full path file names i.e.

$home> vi abcd.txt
/a/b/c/r1.txt
/q/w/e/r2.txt
/z/x/c/r3.txt

Now I want to retrieve only the directory path name for each row
i.e

/a/b/c/
/q/w/e/

How to get the same through shell script?
I have done till now:

while read file
do
  cd  <here need the directory path for each row>
  .. do some common operation ...
done < abcd.txt

Note:
Previously Franklin suggested for getting only the file name to use:

"${file##*/}"

Please help!:confused:

man dirname

1 Like

achenle,
can you help -
i have done this:

while read file
do
  dir = `dirname $file`
  print $dir
done < latest.txt

but i am getting error!

---------- Post updated at 04:02 PM ---------- Previous update was at 03:54 PM ----------

well it got solved! Thanks!

$ for F in /a/b/c/r1.txt /q/w/e/r2.txt /z/x/c/r3.txt; do echo ${F%/*}/; done
/a/b/c/
/q/w/e/
/z/x/c/

Another way: Remove the base filename you found with ${file##*/}. This method does not delete the trailing soidus.

for file in "/a/b/c/r1.txt" "/q/w/e/r2.txt" "/z/x/c/r3.txt"
do
        echo "${file%%${file##*/}}"
done

/a/b/c/
/q/w/e/
/z/x/c/
$ ruby -ne 'puts File.dirname($_)' file
/a/b/c
/q/w/e
/z/x/c

1 Like

Hi methyl,

Could you explain echo "${file%%${file##*/}}" command

Firstly the syntax with $(variable##pattern} and ${variable%%pattern) are in the "man" pages for Posix shells.

In your original post you used ${file##*/} to remove the leading path portion from ${file}. Here we are taking the result from that elimination and removing it from the end of ${file} to leave the path.

echo "${file%%${file##*/}}"

It could equally be done in two stages and been easier to read.
There will no doubt be a better method.

Forgot to mention. In day-to-day scripting I actually prefer "dirname" and "basename" because any scripter understands that method.