Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extract data from file

Status
Not open for further replies.

alhassani54

Programmer
Aug 1, 2002
27
GB
Hi
I would like to extract data from a file. The delimiter is space but some time the file contains more than one space. I tried to use the cut command and use the space as delimiter but unfortunately on some occasion does not work because the file contains more than one space.

Example of the file

1 abc 12345678 12/12/1991 12:39 abc.src
2 def 123 12/12/1991 12:29 defxxxx.src

from example 1 I would like to get 12345678 and abc.src
from example 2 I would like to get 123 and defxxxx.src

Any help will be appreciated.
Thank you

Kais
 
cat file | perl -pe '(undef, $val1, undef, $val2) = split; print $val1 . "\t" . $val2 . "\n";'

In perl, the split operator defaults to splitting on whitespace, the actual number of spaces and the type of whitespace are irrelevant, unless you expicitly specify.
I have assumed you only want fields 2 and 4, therefore the values of fields one and three have been set to undef so that they are silently ignored forever :).

Hope this helps.
 
Awk should be cheaper than perl for such a simple task:
Code:
awk '{print $3, $6}' file

You could use cut if you first replace all adjacent spaces by a single space:
Code:
cat file | tr -s ' ' ' ' | cut -d' ' -f 3,6
 
Another way without using perl would be to use tr to translate all occurrences of spaces to one space only, then do your cut, as follows:

cat file | tr -s ' ' ' ' | cut -d ' ' -f 3,6

' ' indicates a space (I mention this because this font sometimes compresses the spaces). HTH.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top