tags:

views:

54

answers:

5

hi all

I have two different questions(on both questions need to ignore spaces)

How to print all lines until "=" separator for example

    echo " bla bla girl man dog = black white color bla 123 4" | sed/awk .....

Will print:

    bla bla girl man dog

the second question

How to print all lines from "=" until end of line

    echo " bla bla girl man dof = black white color bla 123 4" | sed/awk .....

Will print

    black white color bla 123 4

THX for help Lidia

+1  A: 

You can try this:

echo " bla bla girl man dog = black white color bla 123 4" | awk -F '=' '{print $1}'
Teodor Pripoae
+1  A: 

cut can help you. cut cuts a line using a custom delimiter, and gives you any parts around it.

echo " bla bla girl man dof = black white color bla 123 4" | cut -d= -f1 gives you the first part before a =

echo " bla bla girl man dof = black white color bla 123 4" | cut -d= -f2 gives you the second part after a =

if you have more than one = one the line -f2- will give you everything after the first = (ignoring the second =).

Scharron
A: 

Answer to the first question:

sed 's/^ *\([^=]*\) *= *\(.*\) *$/\1/'

Answer to the second question:

sed 's/^ *\([^=]*\) *= *\(.*\) *$/\2/'

Explanation:

^ *\([^=]*\) *= *\(.*\) *$ matches the whole line. It contains two capturing groups: first group captures everything up to the first = except boundary spaces, second group captures everything after the first = except for boundary spaces. \1 and \2 are references to the capturing groups.

EDIT The above answer to the first question is incorrect, as it leaves trailing spaces. A correct version should read:

sed 's/^ *\([^=]*\) *= *\(.*\) *$/\1/' | sed 's/ *$//'

There seems to be no way to make the [^=]* reluctant, hence two sed commands.

Bolo
@lidia Please check the updated answer.
Bolo
A: 

For the first, use

cut -d= -f1

For the second, use

cut -d= -f2-

But these solutions preserve spaces.

lhf
A: 

With sed:

First question:

echo " bla bla girl man dog = black white color bla 123 4" | sed -n '{s/\([^=]*\)=.*/\1/p}'

Second question:

echo " bla bla girl man dog = black white color bla 123 4" | sed -n '{s/[^=]*=\(.*\)/\1/p}'

With awk:

First question:

echo " bla bla girl man dog = black white color bla 123 4" | awk -F= '{print $1}'

Second quetion:

if you have exactly one = in each line:

echo " bla bla girl man dog = black white color bla 123 4" | awk -F= '{print $2}'

Using cut

echo " bla bla girl man dog = black white color bla 123 4" | cut -d= -f1
Ehsan