Get a substring from a file using the sed command

Can someone help me get a substring using a sed program?

I have a file with this line:

.... define("BASE", "empty"); # there can be any string (not only "empty"). .... 

And I need to get "empty" as a string variable for my bash script.

At this moment I have:

 sed -n '/define(\"BASE\"/p' path/to/file.ext # returns this line: # define("BASE", "empty"); # but I need 'empty' 

UPD: Thanks @Jaypal

At the moment I have a bash script:

 DBNAME=`sed -n '/define(\"BASE\"/p' path/to/file.ext` echo $DBNAME | sed -r 's/.*"([a-zA-Z]+)".*/\1/' 

It works fine, but if there is a way to do the same manipulation with a single line of code?

+4
source share
4 answers

You have to use

 sed -n 's/.*\".*\", \"\(.*\)\".*/\1/p' yourFile.txt 

which means something ( .* ) followed by something in quotation marks ( \".*\" ), then a comma and a space ( , ), and then again something inside quotation marks ( \"\(.*\)\" ).

The brackets define the part that can be reused later, i.e. string in second quotation marks. used it with \1 .

I put -n in front to answer the updated question in order to access the line that was being manipulated.

+5
source

This should help -

 sed -r 's/.*"([a-zA-Z]+)"\);/\1/' path/to/file.ext 

If you enjoy using awk , you can try the following:

 awk -F\" '/define\(/{print $(NF-1)}' path/to/file.ext 

Update:

 DBNAME=$(sed -r '/define\(\"BASE\"/s/.*"([a-zA-Z]+)"\);/\1/' path/to/file.ext) 
+3
source
  sed -nr '/^define.*"(.*)".*$/{s//\1/;p}' path/to/file.ext 
+1
source

if your file does not change over time (i.e. line numbers will always be the same ), you can take a line and use delimiters to take part:

 `sed -n 'Xp' your.file | cut -d ' ' -f 2 |cut -d "\"" -f 2` 

Assuming X is the line number of your desired line

0
source

Source: https://habr.com/ru/post/1390788/


All Articles