LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   How to pass sed address by shell variable? (http://www.linuxquestions.org/questions/programming-9/how-to-pass-sed-address-by-shell-variable-895180/)

kaz2100 08-02-2011 06:41 PM

How to pass sed address by shell variable?
 
Hya,

Situation:
Code:

>cat tux
L
I
N
U
X
>cat tux | sed -e '2s/./<&>/'
L
<I>
N
U
X

Goal: The address for sed s command, (this case 2), need to be supplied by shell variable, like the code below.
Incorrect shellscript
Code:

#!/usr/bin/tcsh
sed -i -e "{$1}s/./<&>/" tux

I think this should work, but not. Then, after several try-and-errors I found that
Code:

sed  -e $1's/./<&>/'
works, but it looks ugly.

I am somewhat confident that there is a neater way.

Question: Does anybody know the answer?

cheers

ta0kira 08-02-2011 07:13 PM

Quote:

Originally Posted by kaz2100 (Post 4432067)
Code:

sed  -e $1's/./<&>/'
works, but it looks ugly.

I am somewhat confident that there is a neater way.

Question: Does anybody know the answer?

With shell scripting the truth is often ugly. There isn't much room for improvement besides sed -e "$1"'s/./<&>/'. This would certainly complicate writing an actual #!/bin/sed script; I'm surprised referencing the environment isn't a standard part of sed (although $1 isn't inherited). I think your problems with "" stem from tcsh syntax because sed -i -e "{$1}s/./<&>/" tux is acceptable in bash.
Kevin Barry

crts 08-02-2011 08:01 PM

Hi,

try this:
Code:

#!/usr/bin/tcsh
sed -i -e "${1} s/./<&>/" tux

Notice, that the curly braces do NOT enclose the '$'.

kaz2100 08-02-2011 08:21 PM

Hya,

Thanks,

ta0kira: Yes, often shell scripts are ugly. As you mentioned, I do not want unnecessarily complicated scripts, nor error prone ones.

crts: Yes, you are a star!

cheers


All times are GMT -5. The time now is 01:24 PM.