I have a file that is returning the following text:
grep -m 1 -o '.*' filename | cut -d ':' -f

I tried the above and I can get just 1 single line of output.

However when I tried with

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

I get the above.

If I want to get just the 2nd line

Is there any way to do it?


5 Answers 5

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

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


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

respectively, to avoid unnecessarily processing later lines.

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


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.


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).
  • 2
    possibly easier to read: sed -n 2p Oct 27, 2020 at 1:40
  • Definitely easier. That's what steeldriver uses in their answer. Oct 27, 2020 at 6:05

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

    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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.