-   Linux - Newbie (
-   -   how to use variable in sed command ? (

anandg111 01-09-2012 05:22 AM

how to use variable in sed command ?
I want to use variable in sed with the option p.
here is my code

while [ $counter -lt 4 ]
sed -n $counter p /tmp/file1

but this codeis not working. it is throwing the below error.

sed: 1 is not a recognized function.

please help me


druuna 01-09-2012 06:18 AM


Have a look at this:

while [[ $counter < 4 ]]
 sed -n "${counter}p" /tmp/file1
 let counter=$counter+1

The curly brackets are needed, otherwise bash thinks it is using counterp instead of counter.

Also fixed some other problems in the posted code snippet.

Hope this helps.

David the H. 01-09-2012 11:52 PM

1) Please use [code][/code] tags around your code and data, to preserve formatting and to improve readability.

2) QUOTE ALL OF YOUR VARIABLE SUBSTITUTIONS. You should never leave the quotes off a variable expansion unless you explicitly want the resulting string to be word-broken by the shell. This is a vitally important concept in scripting, so train yourself to do it correctly now. You can learn about the exceptions later.

As you can see, the solution to your sed problem also comes from understanding proper quoting. (BTW, re druuna's post, the brackets aren't necessary if you separate the "p" from "counter", as sed ignores spaces between letter commands. You got the error you did because the entire expression needs to be passed to sed as a single unit.)

3) It's recommended to use ((..)) for numerical tests, and [[..]] for string tests and other complex expressions. Don't use the old [..] test unless you specifically need POSIX-style portability.

4) In this case, a c-style for loop would be better than a while loop. You can completely avoid the test and manually incrementing the variable.


for (( cnt=1 ; cnt < 4 ; cnt++ )); do
        sed -n "$cnt p" /tmp/file1

5) When you get a chance, read through the whole BashGuide. It covers all the basic concepts in bash scripting, in an easy-to-read format.

David the H. 01-11-2012 11:27 AM

You know, I just noticed...if all you want to do is print a range of lines from the file (or apply some expression to them), there's no need to run a loop. sed can be told to address a range of lines, as well as a single one.



sed -n "$cnt1,$cnt2 p" /tmp/file1

Here are a few useful sed references.

All times are GMT -5. The time now is 11:36 AM.