termlim
termlim

Reputation: 1165

Bash: How to get the n-th line of a file within a for-loop without the usage of sed or awk

In bash, is there a way to dynamically get the n-th line of a file within a for-loop as the loop iterates using head and/or tail commands?

Given a fruits.txt file that contains the following lines:

apple
orange
watermelon
peach

This is an example of what I'm trying to achieve:

for (( i=0; i<someValue; i++ ))
do
  value="$(head -i fruits.txt)"
  echo $value
done

Where the program prints the file line-by-line

Upvotes: 0

Views: 100

Answers (1)

user000001
user000001

Reputation: 33317

This question doesn't make much sense, as it excludes sed and awk which would be the obvious answers, and also restricts the solution to a for loop, whereas a while loop is the more usual choise.

But to answer it literally, you can do something like this:

cat fruits.txt 
apple
orange
watermelon
peach

$ cat script.sh 
#!/bin/bash
someValue=3
for (( i=1; i<=someValue; i++ ))
do
  value=$(head -n "$i" fruits.txt | tail -n 1)
  echo "$value"
done

$ ./script.sh 
apple
orange
watermelon

Upvotes: 1

Related Questions