Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting string between two slashes using sed [duplicate]

I am trying to use sed to extract a specific string from a line within a file. Currently I am reading in a file with a while loop and searching for a specific string. When that string is found I am extracting it, but I then need to use sed to parse the output so that I only get the string between two slashes (Its a directory name, so I need to keep both the starting and trailing slashes if possible). Here is the loop I am running to search for a file:

#!/bin/sh
file=configFile.conf
while read line 
do
    if  echo "$line" | grep -q "directory_root" 
    then DIR_ROOT="$line"
fi
done < "$file"
echo $DIR_ROOT
exit 0

The while loop works and echoes the following string:

directory_root /root/config/data/

I then need to use sed in order to get the following output in order to pass the correct directory name in to another script:

/root/

Is it possible to use sed and regular expressions to extract only the above from the echoed output?

Thanks

like image 720
user1161118 Avatar asked Jun 04 '26 15:06

user1161118


1 Answers

If you want to use sed, this would work:

~/tmp> str="directory_root /root/config/data/"
~/tmp> echo $str | sed 's|^[^/]*\(/[^/]*/\).*$|\1|'
/root/

Or a single liner (assuming directory_root literal is in the line:)

 cat file | sed -e 's|^directory_root \(/[^/]*/\).*$|\1|;tx;d;:x'

Explanation of regex in first example:

s| : using the | as the dilimiter (makes it easier to read in this case)

^ : match beginning of line

[^/]* : match all non / characters (this is greedy so it will stop when it hits the first /.

\( : start recording string 1

/ : match literal /

[^/]* : match all non / charcaters

\) : finish rcording string 1

.* : match everything else to the end of the line

| : delimitter

\1 : replace match with string 1

| : delimitter

In the second example, I appended the ;tx;d;:x which does not echo lines that do not match see here. You can then run this on the entire file, and it will only print the lines it modified.

~/tmp> echo "xx" > tmp.txt
~/tmp> echo "directory_root /root/config/data/" >> tmp.txt
~/tmp> echo "xxxx ttt" >> tmp.txt
~/tmp>
~/tmp> cat tmp.txt | sed -e 's|^directory_root \(/[^/]*/\).*$|\1|;tx;d;:x'
/root/
like image 93
HardcoreHenry Avatar answered Jun 06 '26 07:06

HardcoreHenry