0

Suppose, I have a file called source.txt which has the following data in it:

3LWXA       199  XRAY        1.100    0.12    0.14
3LX3A       180  XRAY        1.550    0.15    0.17
3LY0A       364  XRAY        1.399    0.17    0.19
3LYDA       161  XRAY        1.450    0.17    0.19
3LYEA       307  XRAY        1.300    0.13    0.17
3LYHB       126  XRAY        1.600    0.17    0.21
3LYPA       215  XRAY        1.600    0.18    0.21
3M07A       618  XRAY        1.400    0.15    0.17
3M0FA       213  XRAY        1.600    0.21    0.22

I want to extract {1st} and {1st, 2nd} columns from source.txt and save them into one.txt and two.txt.

How can I do that?


N.B. I found this thread but that didn't help.

1
  • what is the field separator? Tab(s)/Space(s)? main thing that it didn't work is because you didnt' provide the command with correct field delimiter . Feb 18, 2022 at 10:41

5 Answers 5

6

Try also

awk '{print $1 > "one.txt"; print $1,$2 > "two.txt"}' source.txt
1
  • Good for two reasons: (1) Efficiency, only reads the input once, and therefore also (2) Works in a pipeline. Feb 18, 2022 at 10:31
3

Use awk.

awk '{ print $1 }' source.txt > one.txt
awk '{ print $1,  $2 }' source.txt > two.txt
0
2

With GNU sed utilizing it's extended regex features enabled (-E), we can use the following:

sed -En 's/\S+/&\n/2
  s/\n.*//wfile2
  s/\s.*//wfile1
' file
0

Can also do with cut command:

cat source.txt | sed 's/[ ]\+/:/g' | cut -d ":" -f 1 > one.txt
cat source.txt | sed 's/[ ]\+/:/g' | cut -d ":" -f 1-2 | tr ":" " " > two.txt
0
#!/usr/bin/python
import re
res=re.compile(r'\s+')
fil=open('source.txt','r')
firs=open('one.txt','w')
sec=open('two.txt','w')
for f in fil:
    splitcomp=re.sub(res," ",f).strip().split(' ')
    firs.write(splitcomp[0].strip() + "\n")
    seondfilecon="{0}\t{1}".format(splitcomp[0],splitcomp[1])
    sec.write(seondfilecon.strip()+"\n")

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .