Hari
Hari

Reputation: 1

UNIX: Grep a specific word and all the text following it

I have a variable in Unix, that stores multiple lines of alpha-numeric characters. I want to grep to a specific word and get all the text following it.

For example, $Variable contains:

Hello, User

Your files are:

File1 : Exists

File2 : None

Let us say I want to find File2, which is the last line and I want if it is Yes or None or whatever text is present after the colon and save it to another variable.

Upvotes: 0

Views: 1027

Answers (4)

Ed Morton
Ed Morton

Reputation: 203189

grep is to Globally search for a Regular Expression and Print the matching string. That is not what you want to do, you want to take a Stream of input and EDit it to output part of it. Guess what tool does THAT in UNIX.

$ echo "$var"
Hello, User

Your files are:

File1 : Exists

File2 : None
$ var2=$(echo "$var" | sed -n 's/^File2 : //p')
$ echo "$var2"
None

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753515

Given:

variable="Hello, User
Your files are:
File1 : Exists
File2 : None"

You can get the information for File2 into another variable file2 using:

file2=$(echo "$variable" | sed -n '/File2/ s/File2 *: *//p')

The double quotes preserve newlines in the variable. The -n suppresses the default printing. The pattern matches the line containing File2 followed by any number of spaces, a colon and any number of additional spaces; it is replaced by nothing, and the remainder of the line is printed by sed and that is captured in the variable file2. If there can be spaces in front of File2 in the data, you can arrange to match and remove them too.

Upvotes: 0

Rob
Rob

Reputation: 2656

Use sed instead

sed -n '/the word you are looking for/,$p' <file name>

or since you said it was in a variable something more like:

echo "$variable" | sed -n '/the word you are looking for/,$p'

sed -n says do not print.

the pattern says from "the word you are looking for" to $ which is the end of file do the p command which is print :)

If you have to stop before the end of the file then you have to replace $ with the end pattern

If you just want to save the results to another variable:

new_variable=$(echo "$variable" | sed -n '/the word you are looking for/,$p')

Also note that is the string you are looking for has / in it then you must escape it with \ so it would look like

new_variable=$(echo "$variable" | sed -n '/the word you are\/ looking for/,$p')

Upvotes: 2

mauro
mauro

Reputation: 5940

So you have a variable defined as:

$ var="abc\ndef\nghi\njkl\nmn"

Then, if you want to print "line" containing "ghi" and following this way:

$ echo -e $var | sed -n '/ghi/,$p'

Upvotes: 1

Related Questions