Operating System - HP-UX
1758295 Members
2215 Online
108868 Solutions
New Discussion юеВ

sed variable substitution NOT to match any lines?

 
SOLVED
Go to solution
A. Daniel King_1
Super Advisor

sed variable substitution NOT to match any lines?

Hi, folks,

I've got a script that defines a string, say:

x=abc123

and then modifies a file based upon a one-line sed script:

sed "1,/$x/ d" infile > outfile

...

Here is the kicker: How do I define $x so that the sed script matches NO lines? I want, under certain circumstances, for the input file to exactly match the output file.

This would be an easy extra line or two to implement, but sed probably has some very easy way to do this internally.

Thanks in advance.
Command-Line Junkie
7 REPLIES 7
Anthony deRito
Respected Contributor

Re: sed variable substitution NOT to match any lines?

Jose Mosquera
Honored Contributor

Re: sed variable substitution NOT to match any lines?

Hi,

Pls try this:

cat infile|sed 's/$x/ d/g' > outfile

This replace string contened in $x (abc123) by " d" string (space an letter d), note that quotes must be single.

Rgds.
James R. Ferguson
Acclaimed Contributor
Solution

Re: sed variable substitution NOT to match any lines?

Hi:

I don't think you can get there from here!

Assuming that you *only* change the value of $x then the best you can do is only delete the first line from the output string:

Consider:

# x=
# sed "1,/$x/d" /etc/hosts > /tmp/hosts
# diff /etc/hosts /tmp/hosts

...you will see that only the first line has been deleted.

Regards!

...JRF...
Sridhar Bhaskarla
Honored Contributor

Re: sed variable substitution NOT to match any lines?

I second JRF.

You will need to go with a small if statement to verify the value of 'x' and based on it use the sed statement.

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
H.Merijn Brand (procura
Honored Contributor

Re: sed variable substitution NOT to match any lines?

To match exactly, you will need anchors

sed "1,/^$x\$/d" infile >outfile

or in perl

perl -ne "m{^$x\$} or print" infile >outfile

or in grep

grep -v "^$x\$" infile >outfile
Enjoy, Have FUN! H.Merijn
A. Daniel King_1
Super Advisor

Re: sed variable substitution NOT to match any lines?

I ended up doing:

x="1,/abc123/ d"

and sometimes

x=":"

sed "$x" infile > outfile

Thanks for the feedback, folks.
Command-Line Junkie
Thomas M. Williams_1
Frequent Advisor

Re: sed variable substitution NOT to match any lines?

Whenever you use a variable substitution in a command like sed you need to quote it with single ticks. It appears you are trying to delete lines containing the value of $x.

To delete lines:
sed '/'$x'/d' infile > outfile

To substitute all lines:
sed '1,$s/'$x'/whatever/'

Hope this helps.

I Think the Clock is Slow ...