Espector
Espector

Reputation: 451

Extract part of a path

I have a variable that is a path of a windows folder.

I would like to handle the way with SED .

Example:

Input:

\\computer1\folder$

Output:

computer1

I would always pick the host name that is between \\ and \

Could someone give me a light?

Upvotes: 1

Views: 2123

Answers (4)

slitvinov
slitvinov

Reputation: 5768

With awk. s stands for "separator" and a stands for "any".

echo '\\computer1\folder$' | \
awk '{s="\\\\"; a=".*"; sub(a s s, ""); sub(s a, ""); print}'

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

You can do this in a POSIX compatible shell:

% folder='\\computer1\folder$'
% folder="${folder/\\\\/}" # Remove leading '\\'
% printf "%s\n" "${folder%%\\*}"
computer1

Alternative with Bashism:

% folder='\\computer1\folder$'
% [[ "$folder" =~ '\\'([^\\]*) ]]
% printf "%s\n" "${BASH_REMATCH[1]}"
computer1

Upvotes: 1

Utsav
Utsav

Reputation: 8093

For this scenario, awk is a better option. Use awk -F'\' '{print $2}'

Example

$> echo "\\computer1\folder$"|awk -F'\' '{print $2}'

Output

computer1

Or you can try putting it with a variable.

$> export val="\\computer1\folder$"

$> echo $val|awk -F'\' '{print $2}'
computer1

Upvotes: 0

SLePort
SLePort

Reputation: 15461

With sed :

$ sed 's/\\\\\([^\]*\)\\.*/\1/' <<< '\\computer1\folder$'
computer1

The basic syntax for sed substitution command is s/oldtext/newtext/.

  • s is for substitution command
  • in the path string, every \ must be escaped so it becomes \\
  • \([^\]*\)\ captures every non \ character until next \
  • the captured string is output with backreference \1

Upvotes: 0

Related Questions