Arpan
Arpan

Reputation: 993

Searching a column in a unix file?

I have the data file below:

136110828724515000007700877  
137110904734015000007700877  
138110911724215000007700877  
127110626724515000007700871  
127110626726015000007700871  
131110724724515000007700871  
134110814725015000007700871  
134110814734015000007700871  
104110122726027000001810072  
107110208724527000002900000

And I want to extract value of column 3 ie values of 6787714447. I tried by using:-

awk "print $3" <filename>

but it didn't work. What should I use instead?

Upvotes: 1

Views: 1270

Answers (2)

Goncalo
Goncalo

Reputation: 362

Cut is probably the simpler/cleaner option, but here two alternatives:

AWK version:

awk '{print substr($1, 3, 1) }' <filename> 

Python version:

python -c 'print "\n".join(map(lambda x: x[2], open("<filename>").readlines()))'

EDIT: Please see 1_CR's comments and disregard this option in favour of his.

Upvotes: 1

fedorqui
fedorqui

Reputation: 289505

It is a better job for cut:

$ cut -c 3 < file
6
7
8
7
7
1
4
4
4
7

As per man cut:

-c, --characters=LIST

select only these characters

To make them appear all in the same line, pipe tr -d '\n':

$ cut -c 3 < file | tr -d '\n'
6787714447

Or even to sed to have the new line at the end:

$ cut -c 3 < file | tr -d '\n' | sed 's/$/\n/'
6787714447

With :

$ grep -oP "^..\K." file
6
7
8
7
7
1
4
4
4
7

with :

$ sed -r 's/..(.).*/\1/' file
6
7
8
7
7
1
4
4
4
7

with :

$ awk '{split ($0, a, ""); print a[3]}' file
6
7
8
7
7
1
4
4
4
7

Upvotes: 6

Related Questions