Print 2nd line in text file

Solution 1:

head -2 filename | tail -1 | cut -d ':' -f 1   

Solution 2:

I'd suggest awk for this kind of task:

awk -F: 'NR==2 {print $1}' filename

Alternatively with sed:

sed -n '2s/:.*//p' filename

If the file is large, you may want to change those to

awk -F: 'NR==2 {print $1; exit}' filename

and

sed -n '2{s/:.*//p;q;}' filename

respectively, to avoid unnecessarily processing later lines.

Solution 3:

grep -m 2 -o '.*' filename | cut -d ':' -f 1 | tail -n 1

Results:

10.10.10.170

tail -n 1 prints only the last line of the results of grep -m 2 -o '.*' filename | cut -d ':' -f 1

The original text file is named filename.

Solution 4:

You can use this sed command:

sed -e '2!d' -e 's/:.*//' filename

or, in a bit more compact way:

sed '{2!d; s/:.*//; q;}' filename
  • 2!d tells sed to delete (d) all lines except (!) the second (2) line.
  • 's/:.*//' tells sed to remove everything after : (including :).
  • In the second case q is used to terminate the operation immediately after it's completed (useful for larger files - thanks @JoL for the suggestion).

Solution 5:

You can do it purely with the shell (assuming bash), without the use of any other utilities:

{
    read
    IFS=: read ip port
    echo $ip
} < input.txt

Starting at the end, the < redirects input.txt to the { } command group. The first read then reads 1 line and discards it. The second read reads the next line, and IFS separates it by colon :. The second read populates the ip and port variables with the 1st and 2nd elements of the second line. The $ip variable is the output by echo.