1

Example:

3|100|[email protected]|0|0|6:1,10,11,12,13,2,3,4,5,6,9|7:1,10,11,13,16,2,4,5,6,9|

Expected view after grep:

[email protected]
0

5 Answers 5

8

Use cut:

$ echo '3|100|[email protected]|0|0|6:1,10,11,12,13,2,3,4,5,6,9|7:1,10,11,13,16,2,4,5,6,9|' |\
cut -d'|' -f3
[email protected]
1
4

Why grep? Use cut

echo "3|100|[email protected]|0|0|6:1,10,11,12,13,2,3,4,5,6,9|7:1,10,11,13,16,2,4,5,6,9|" | cut -d '|' -f 3
4

Maybe awk is better suited for this usage:

awk 'BEGIN { FS = "|" } ; { print $3 }'

If you have to extract more than one field from such an input, I think it is the easiest using awk.

(OFF: excuse me if I pointed in an awk-ward direction)

4
  • Maybe? Why do you think so?
    – user95605
    Oct 11, 2012 at 12:06
  • 1
    Extracting multiple fields is possible with cut: cut -d'|' -f3-5
    – user95605
    Oct 11, 2012 at 12:10
  • 2
    From my previous experiences, I assumed that either the poster, or someone else finding this page will face the issue that more than one column is required from the input. But a less complicated tool (cut) might be faster than universal ones (awk), if the restricted feature set of the lighter tool is adequate. (I don't have data to back this) Also, for me, the awk command is more readable. If I ever had to re-read the script written, I'd like to see the awk line in favor of the others - but that is just a personal opinion, not an objective fact. That's why only 'maybe'.
    – ppeterka
    Oct 11, 2012 at 12:18
  • 2
    +1 Sorry, I had not done my homework on cut, thanks for pointing that out!
    – ppeterka
    Oct 11, 2012 at 12:19
2

Just Imagine your content is present under this file file1

[max@localhost ~]$ cat file1 3|100|[email protected]|0|0|6:1,10,11,12,13,2,3,4,5,6,9|7:1,10,11,13,16,2,4,5,6,9|

To cut the third field use this command

[max@localhost ~]$ cut -d "|" -f3 file1

[email protected]

Here

-d : Specifies to use character | as delimiter

-f1 : Print first field, if you want print second field use -f2, third field use -f3, and so on...

suppose file1 content is like this

[max@localhost ~]$ cat file1

root:x:0:0:root:/root:/bin/bash

Then we have to use : as delimiter like this

To cut first field use f1

[max@localhost ~]$ cut -d ":" -f1 file1
root

To cut second field use f2

[max@localhost ~]$ cut -d ":" -f2 file1
x

To cut third field use f3

[max@localhost ~]$ cut -d ":" -f3 file1
0
0
2

Just for fun, here's how you could do it with grep and tr:

<infile grep -Eo '^([^|]+\|){3}' | grep -Eo '[^|]+\|$' | tr -d '|'

The first regex grabs the first three pipe delimited fields. The second grep picks out the last field and tr removes the remaining delimiter.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .