Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get substring from file using "sed"

Can anyone help me to get substring using 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 string variable to 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 to @Jaypal

For now I have bash script:

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

It work OK, but if there any way to make the same manipulation with one line of code?

like image 612
Arthur Halma Avatar asked Jan 13 '12 08:01

Arthur Halma


People also ask

How do you get a specific line from a file Linux?

Using the head and tail Commands The idea is: First, we get line 1 to X using the head command: head -n X input. Then, we pipe the result from the first step to the tail command to get the last line: head -n X input | tail -1.


3 Answers

You should use is

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

which means something (.*) followed by something in quotes (\".*\"), then a comma and a blank space (,), and then again something within quotes (\"\(.*\)\").

The brackets define the part that you later can reuse, i.e. the string within the second quotes. used it with \1.

I put -n front in order to answer the updated question, to get online the line that was manipulated.

like image 142
ezdazuzena Avatar answered Oct 01 '22 11:10

ezdazuzena


This should help -

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

If you are ok with using awk then 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)
like image 32
jaypal singh Avatar answered Oct 01 '22 10:10

jaypal singh


 sed -nr '/^define.*"(.*)".*$/{s//\1/;p}' path/to/file.ext
like image 25
Sidharth C. Nadhan Avatar answered Oct 01 '22 10:10

Sidharth C. Nadhan