0

I'm trying to write a shell script that outputs the nth line from a file called file.txt, but I keep getting various errors; one of them including

Line 7: [: 10 file.txt: integer expression expected

and so I cant seem to make it work. What am I doing wrong?

# Read from the file file.txt and output the tenth line to stdout.
#!/bin/bash

len=`wc -l file.txt`
echo $len

if [ "$len" -lt 10 ]
then
    errormessage="File too short"
    echo $errormessage
    exit 0
fi

var=`sed '10q;d' file.txt`
echo $var
7
  • 2
    Try typing wc -l file.txt into your shell. What do you see? Is it just a number? Commented Jun 8, 2018 at 18:43
  • 1
    Capturing the output to a variable so you can output it is obviously redundant. Commented Jun 8, 2018 at 18:47
  • @triplee: If you are going to do it, you better quote the expansion. Commented Jun 8, 2018 at 18:48
  • 1
    @Devam: A lot of the issues in your script(s) could be detected by passing them through shellcheck.net. It's usage is highly recommended. Commented Jun 8, 2018 at 18:48
  • Yeah, I was just going to post another comment with a link to stackoverflow.com/questions/10067266/… Commented Jun 8, 2018 at 18:49

3 Answers 3

1

wc -l file... prints the number of lines and the filename for each filename listed as an argument

If no filenames are listed, wc -l reads from standard input and just prints the number of lines.

In short, use

len=$(wc -l < file.txt)

Note the redirection so that stdin is used instead of naming the file on the command line.

And try to completely forget that backticks exist: their usage has been deprecated for aeons. Use the $(...) syntax as shown.

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

2 Comments

Still the entire script could be an Awk one-liner... maybe two-liner.
@triplee: could be many kinds of one-liner, including tail -n+10 | head -n1
0

Instead of just giving wc -l file.txt give cat file.txt | wc -l. the latter one will return only the number of lines whereas the first one will return the number lines with the file name next to it.

1 Comment

0

Show the tenth line or give an error message and exit:
I will use exit 1, since 0 is normallly ok.
However, in order to have a special returncode for sed, I will make sed return 1 for a match.

errormessage="File too short"
var=$(sed -n '10 {p;q1}' file.txt) && { echo "${errormessage}"; exit 1; }
# You must have spaces above the pipes |    |                       |  |

Comments

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.