venkatsai
venkatsai

Reputation: 123

grep find lines which have "$" only once

I have a file whose contents are

$VARIABLE1 text $VARIABLE2
text $VARIBLE2
$VARIABLE3 TEXT $VARIABLE2
anothertext $VARIBLE2

$VARIABLE2 appears in all lines

I need all the lines that has only $VARIABLE2 so i need the lines where $ exists only once

I tried

cat filename | grep  -F "$\{1\}"

It doesnt give me any output

Upvotes: 1

Views: 180

Answers (3)

Kent
Kent

Reputation: 195139

If you just want to get the lines with single $ sign:

awk -F'$' 'NF==2' file

this awk one-liner will help you.

What it does is: make the $ as the field separator, if there is one and only one $ in a line, the line must be separated into 2 parts (fields).

Upvotes: 3

Toby Speight
Toby Speight

Reputation: 30882

Consider using two commands in a pipeline - one to remove lines with no $ and one to remove those with 2 or more $:

grep -F '$' filename | grep -v '\$.*\$'

P.S. No need to invoke cat - grep will happily accept a filename, or you can redirect its input using <.

Upvotes: 0

iBug
iBug

Reputation: 37267

Easy:

grep '^[^$]*\$[^$]*$' filename

Explained: A line starting with any number of "not dollar" characters, then a dollar, then any number of "not dollar" characters until end.

This ensures you only capture lines with exactly one dollar sign. Note the use of single quotes to prevent bash from expanding the dollar sign.

Upvotes: 1

Related Questions