I am using grep to search out /Users/
in a text file. This is the output:
'dir': u'/Users/dlee/Desktop',
Is there a way to sed out the word after Users/
? That is, to get dlee
as the output?
I am using grep to search out /Users/
in a text file. This is the output:
'dir': u'/Users/dlee/Desktop',
Is there a way to sed out the word after Users/
? That is, to get dlee
as the output?
This should do the job:
sed -n '\@.*/Users/\([^/]*\)/.*@ s//\1/p' text.file
The -n
suppresses output unless data is printed explicitly. The \@
notation replaces the search character (default /
) with @
. Then the search pattern looks for /Users/
followed by a sequence of non-slashes and a slash, capturing the non-slashes (user name); it matches everything else on the line too (the .*
at beginning and end). The s//\1
/p` command replaces what was matched (the whole line) with what was captured (the user name), and prints the information.
Alternatively, you can use a backslash-slash sequence to match the slashes in the data:
sed -n '/.*\/Users\/\([^/]*\)\/.*/ s//\1/p' text.file
You do not need a backslash before the slash in the character class, but the other backslashes are needed. If you were unwise enough to have a user name d\lee
and you included a backslash in the character class, you would not see the name d\lee
in the output.
Potentially, you could also use awk to do achieve the same.
awk -F"/" '/Users/{print $2}' file
The delimiter has been set to /
which will print the second column on rows containing the string "Users
".
With grep and Perl regex:
$ grep -Po '(?<=/Users/)[^/]*' <<< "'dir': u'/Users/dlee/Desktop',"
dlee
-o
returns only the match(?<=/Users/)
is a "positive look-behind", i.e., the match has to be preceded by it but it is not included[^/]*
is any number of characters except forward slashes