Marisa
Marisa

Reputation: 59

BASH: How to store commands with variables into a new variable?

I want to store the ith line of a file (filename stored in variable filename) into a new variable called line where:

filename=$2
i=$1

let's say for this sake i=1 and filename=names.txt):

line="$(sed '1q;d' names.txt)"

How would I store the actual filename and i variable?

Upvotes: 0

Views: 38

Answers (1)

CS Pei
CS Pei

Reputation: 11047

Is this what you want?

line=$(sed "${i}q;d" $filename)

For example,

$filename="a.txt"

i=1

line=$(sed "${i}q;d" $filename)

echo $line 
aaa

a.txt like this:

aaa
bbb

The key is that you need double quotes for ${i} otherwise you will get errors.

Upvotes: 2

Related Questions