How to grep column after second pipe
Solution 1
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]
Solution 2
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
Solution 3
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)
Solution 4
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.
Solution 5
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
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
Comments
-
Kalin Borisov over 1 year
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]
-
Augamire over 11 yearsThat's the Un*x spirit: small tools that do one task well. wiki.debian.org/TheUnixWay faqs.org/docs/artu/ch01s06.html
-
Admin over 11 yearsMaybe? Why do you think so?
-
Admin over 11 yearsExtracting multiple fields is possible with
cut
:cut -d'|' -f3-5
-
Admin over 11 yearsFrom 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'.
-
Admin over 11 years+1 Sorry, I had not done my homework on cut, thanks for pointing that out!