LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   passing variables to sed (http://www.linuxquestions.org/questions/programming-9/passing-variables-to-sed-76978/)

jjfate 07-29-2003 12:22 PM

passing variables to sed
 
Is there a way to pass variables to sed? I would like to present a user with a list with line numbers, then prompt the user for the line number that they would like to delete. I thought that I would like to use sed to delete that line, here is what I had in mind:


cat list | more

echo "Enter line number to be deleted..."
read myNum
sed -e $myNumd


I know that I can do this to delete line 5

sed -e 5d

but I am having trouble passing variables. Any ideas? Or other solutions?

JJ

Tinkster 07-29-2003 05:44 PM

Something like
Code:

#!/bin/bash                                                                   
cat blah.txt | more

echo "Enter line number to be deleted..."
read myNum
cat blah.txt | sed -e "$myNum"d > blah.txt
cat blah.txt

?

Cheers,
Tink

jjfate 07-30-2003 01:34 PM

Tinkster,

Perfect, thank you very much it worked great!


JJ

Strike 07-30-2003 02:44 PM

Code:

[ddipaolo@quinn ~]% echo -e "1\n2\n3\n4\n" > temp.txt
[ddipaolo@quinn ~]% cat temp.txt
1
2
3
4

[ddipaolo@quinn ~]% export LINENUM=3
[ddipaolo@quinn ~]% sed -e `echo $LINENUM`d temp.txt
1
2
4

[ddipaolo@quinn ~]%

You get -1 point for gratuitous cat'ing to sed :) Also, I'm not so sure those quotes will work for everything in general, but if it works for you great. If not, above is what I did.

Tinkster 07-30-2003 03:08 PM

But your solution doesn't write back to
the same file ;)

Cheers,
Tink

Strike 07-30-2003 10:51 PM

So redirect it to the file ...

Tinkster 07-30-2003 11:36 PM

Well done :)

Results in an empty file ...

Cheers,
Tink

Strike 07-31-2003 01:56 AM

Quote:

Originally posted by Tinkster
Well done :)

Results in an empty file ...

Cheers,
Tink

What?

Code:

cat temp.txt | sed -e `echo $LINENUM`d > temp.txt
If you want it to put the results in the same file, of course you'll have to use cat. But for things like piping the output of cat to more, it's just unnecessary. I was just pointing out that sed can work on files directly if you want it to.

Tinkster 07-31-2003 04:15 AM

Quote:

You get -1 point for gratuitous cat'ing to sed
:P

Cheers,
Tink


All times are GMT -5. The time now is 07:09 PM.