1

Say I have the following string in a bash script

"stuff qrg eqrhqe stuff wthwr /this/is/a/full/path/to/a/fils.txt sadf ergwqe"

How can I extract /this/is/a/full/path/to/a/fils.txt from this string in a bash script.

Knowing that:

  1. the extension of the file can change
  2. It might be a directory (so no .ext)
  3. the should be only one "path" in this string to look for
5
  • 1
    Can your full path contain white spaced also? Commented Mar 15, 2017 at 10:28
  • 2
    What did you try for yourself? Commented Mar 15, 2017 at 10:32
  • IMHO, it would be easier to start thinking what would be there in common in the strings you would like to extract. Commented Mar 15, 2017 at 10:40
  • @anubhava good point: no space Commented Mar 15, 2017 at 10:41
  • @Inian I remove before / with sed then tr on ` ` but I look for something authoritative Commented Mar 15, 2017 at 10:42

1 Answer 1

1

You can try this grep -o:

str="stuff qrg eqrhqe stuff wthwr /this/is/a/full/path/to/a/fils.txt sadf ergwqe"
grep -o '/[^[:blank:]]*' <<< "$str" | head -1
/this/is/a/full/path/to/a/fils.txt

head -1 is to ensure we display only first path starting with a /

Sign up to request clarification or add additional context in comments.

4 Comments

what is <<< and why not grep -o regexp "$str" ?
<<< is called here-string, it feeds input as a string to grep comman
what's the advantage over grep -o regexp "$str" ?
grep will consider $str a file in that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.