Reputation: 11
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
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
Reputation: 780724
Variables are expanded inside doublequotes, not inside singlequotes:
sed -n "$variable p" <file>
Upvotes: 3