7

Suppose that we have file like this:

sometext11 sometext12 sometext13 sometext21 sometext22 sometext23

Texts are separated by tabs and we know sometext from column 1 but want to get text from column 2. I know I can get line by:

grep 'sometext11' file.txt

How to get text from second column? Maybe some tool with option -t [column nr]?

bandit
  • 839
  • 4
  • 10
  • 26

4 Answers4

13

awk:

awk '{print $2}' file.txt

cut:

cut -f2 file.txt

bash:

while read -a A; do echo ${A[1]}; done < file.txt

perl:

perl -lane 'print $F[1]' file.txt

If you know the string you are grepping for, you can use grep:

grep -o 'sometext12' file.txt
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
3
awk '{print $2}' < yourfile
Gryphius
  • 75,626
  • 6
  • 48
  • 54
2

You can use cut command

cut -f2
tuxuday
  • 2,977
  • 17
  • 18
0

You don't need grep:

awk '/sometext11/ {print $2}' file.txt

or you can do it all in grep if yours supports Perl Compatible Regular Expressions (PCRE), such as GNU or OS X grep:

grep -Po '(?<=sometext11\t).*?(?=\t.*)' file.txt
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439