user3613346
user3613346

Reputation: 11

How to use a Linux variable as a command parameter

I am trying to use a bash shell variable as a command parameter but can't

Here is what works:

sed -n '2p' <file>   

gives me line 2 of file

What I want to do:

sed -n '$variable p' <file>

Of course, this does not work. I have tried every possible syntax combination without success. How can I incorporate a variable in place of a constant?

Upvotes: 1

Views: 1091

Answers (3)

glenn jackman
glenn jackman

Reputation: 246744

@Barmar has the right answer to your question.

I fear you are going to use this as a technique to iterate over the lines of a file.

This will be very inefficient:

for linenum in $(seq $(wc -l < filename)); do
    line=$(sed -n "$linenum p" filename)
    # do something with $line
done

The idiomatic way to iterate over the lines of a file is:

while IFS= read -r line; do
    # do something with "$line"
done < filename

Upvotes: 1

tburette
tburette

Reputation: 181

Put the variable outside the string: sed -n $variable'p'

Upvotes: 0

Barmar
Barmar

Reputation: 780724

Variables are expanded inside doublequotes, not inside singlequotes:

sed -n "$variable p" <file>

Upvotes: 3

Related Questions