1

I have a file that has a list of paths like so:

"1"       "/user/bin/share"
"2"       "/home/user/.local"
"3"       "/root/"

Is there a way to extract just the paths? I dont want the numbers or quotation marks. How can I sed or grep the paths out of the file? What regex would be required for such a task?

1

4 Answers 4

6

If all the paths start with /, you could just match / followed by a sequence of non-" characters:

$ grep -o '/[^"]*' file
/user/bin/share
/home/user/.local
/root/

Alternatively, for a more structured approach, use awk to strip quotes from and print just the second field:

awk '{gsub(/"/,"",$2); print $2}' file
1
  • awk solution would not work if there was a whitespaces in path Sep 7, 2018 at 4:08
1

Assuming that the paths do not contain newline characters,

$ sed 's/^.*[[:blank:]]"//; s/"$//' <file
/user/bin/share
/home/user/.local
/root/

The sed code first removes everything on each line up to and including the first " character preceded by a blank (space or tab). It then removes the " at the end.

This allows the paths to contain spaces and embedded " characters, but not the combination blank+".

1

Why wouldn't a simple

awk -F\" '{print $4}' file
/user/bin/share
/home/user/.local
/root/

work?

1

Simple approach. Pluck out field #4, with quotes as delimiters, using cut.

$ cut -f4 -d\" file
/user/bin/share
/home/user/.local
/root/
$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.