0

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?

1
  • does this work also for the sed example? ie sed '$iq:d' $filename)" because I get an error for the $i Commented May 25, 2015 at 0:19

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hmm that gives me an error..however that is the output I want
the 1q;d must be in single quotes? not sure if that affects it. ie must be sed '1q;d' names.txt
what environment do you have? what kind of error do you get?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.