7

I have a file that is returning the following text:

10.10.10.160:1111
10.10.10.170:2222
10.10.10.180:3333
grep -m 1 -o '.*' filename | cut -d ':' -f

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

10.10.10.160

However when I tried with

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

I get the above.

If I want to get just the 2nd line

10.10.10.170

Is there any way to do it?

8
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.

| improve this answer | |
25
head -2 filename | tail -1 | cut -d ':' -f 1   
| improve this answer | |
17

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.

| improve this answer | |
8

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).
| improve this answer | |
  • 2
    possibly easier to read: sed -n 2p – D. Ben Knoble Oct 27 at 1:40
  • Definitely easier. That's what steeldriver uses in their answer. – BeastOfCaerbannog Oct 27 at 6:05
0

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.

| improve this answer | |

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.