views:

433

answers:

4

I'm using Windows, and I would like to extract certain columns from a text file using a Perl, Python, batch etc. one-liner.

On Unix I could do this:

cut -d " " -f 1-3 <my file>

How can I do this on Windows?

+2  A: 

That's rather simple Python script:

for line in open("my file"):
    parts = line.split(" ")
    print " ".join(parts[0:3])
Łukasz
Can this be done as a Python one-liner, as requested?
toolic
@toolic, of course. But it will not be as "elegant" since Python is "not meant" to do one liners. Its meant to produce readable code.
ghostdog74
print "\n".join(" ".join(line.split(" ") for line in open("my file"))Ugly one-liner
Łukasz
+1  A: 

The easiest way to do it would be to install Cygwin and use the Unix cut command.

Steven Huwig
its even easy to download and install GNU win32 tools than cygwin.
ghostdog74
+6  A: 

Here is a Perl one-liner to print the first 3 whitespace-delimited columns of a file. This can be run on Windows (or Unix). Refer to perlrun.

perl -ane "print qq(@F[0..2]\n)" file.txt
toolic
Thanks, this was exactly what I needed!
atricapilla
`perl -pane "$_ = qq(@F[0..2])"`
Sinan Ünür
`perl -pane'$_="@F[0..2]"'`
Hynek -Pichi- Vychodil
perl -pale'$_="@F[0..2]"'
sid_com
+3  A: 

you can download GNU windows and use your normal cut/awk etc.. Or natively, you can use vbscript

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strFile = objArgs(0)
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfLine
    strLine=objFile.ReadLine
    sp = Split(strLine," ")
    s=""
    For i=0 To 2
        s=s&" "&sp(i)       
    Next
    WScript.Echo s
Loop

save the above as mysplit.vbs and on command line

c:\test> cscript //nologo mysplit.vbs file

Or just simple batch

@echo off
for /f "tokens=1,2,3 delims= " %%a in (file) do (echo %%a %%b %%c)

If you want a Python one liner

c:\test> type file|python -c "import sys; print [' '.join(i.split()[:3]) for i in sys.stdin.readlines()]"
ghostdog74