0

I need to read into my script 3 parameters, the first 2 are numbers and the third one is a .txt file.

For example:

example.sh 3 2 exam.txt

And with the third parameter exam.txt that already has some text in it I need to search for lines with head and tail.

The question is how do I read that exam.txt? Tried "$3" but when working with it, it only uses the word, not the file.

  • 4
    Do you want to read its contents, or just pass the path to the file to other programs? Also, please include the exact steps you already tried and also what you have researched so far. – Panki Apr 06 '21 at 12:35
  • if you want to dump the content of the life cat $3 will do that for you, however, depending on what you want to do with the content there are better ways to handle this. – Rob Apr 06 '21 at 12:42
  • 2
    Please tell us what you exactly do "when working with it" – pLumo Apr 06 '21 at 12:47
  • For example I need to make a script that will output lines of text from line$1 to line $6 so the first parameter is the starting line and the second parameter is the end line of the output. And the third parameter is going to be a text of my choosing. And from that random text it needs to output those lines. The text of course being some file with the ending .txt – Zijad Bećirević Apr 06 '21 at 12:58
  • Every command you can use to process a file will accept one or more filenames on the command line, either as an argument or via redirection. – Paul_Pedant Apr 06 '21 at 13:14

1 Answers1

1

$3 is just going to be the string of the filename that you're passing the bash script. You will need to do something with that filename string to get anything useful out of it.

If you just need to get the content of the file itself you could cat $3 and that will cat the contents of the filename you've passed as that argument.

If you need to iterate over each line of the file, then you could do something like this:

while IFS= read -r line; do
  echo "$line"  # $line is a variable that represents the current line in the file
done < "$3"

The above example would just echo each line in the file, so you would want to add a counter/logic into the while loop that would allow you to execute whatever you want to do on specific lines and replace the echo statement.

Natolio
  • 1,232