1

Suppose, i having a path and file name in a single line of txt file. below is the example

folder/folder1/folder2/folder3/filename.txt

Now i want to get this whole path so that i can reach to the file. I can get the filename by using awk separated by first '/' reading in reverse order(using NF). But not sure how to get full path.

My output should contain folder/folder1/folder2/folder3

1 Answers1

0

You can do it in a lot of ways, actually...

Let's pretend that you have your line of text in a var named line.

As suggested by @Cyrus, you can use:

dirname "${line}"

Please, note that this will be a relative path, just as you provide it in your txt file. (relative vs absolute path )

If you need a full path, you can use:

line="$(readlink -f "${line}")"
printf "%s" "${line##*/}"

Note that both dirname and readlink are binaries and not built-ins in bash, so they could not work on some system (E.G. macOS). In this case, you can use brew install coreutils to install coreutils. (You can get brew here.)

They however can be considered portable, if you aim for portability.

Hope this helps.

ingroxd
  • 995
  • 1
  • 12
  • 28
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the section "Answer Well-Asked Questions", and the bullet point therein regarding questions which "have already been asked and answered many times before". – Charles Duffy Nov 04 '18 at 20:44
  • BTW, reliance on having *some* kind of `readlink` is indeed reasonably portable, but the `-f` argument is a GNUism; Apple's `readlink` only accepts one option, that being `-n`. Unless one needs to handle the case of a path that doesn't include any `/` at all, consider using [parameter expansion](http://wiki.bash-hackers.org/syntax/pe) anyhow -- `line=${line%/*}` is not only guaranteed to be supported on any POSIX shell, but also is evaluated internally, and is thus much faster than calling out to an external utility. (See also [BashFAQ #100](http://mywiki.wooledge.org/BashFAQ/100)). – Charles Duffy Nov 04 '18 at 20:48