How to get first n characters of each line in unix data file

Teja picture Teja · Jan 22, 2013 · Viewed 83.6k times · Source

I am trying to get the first 22 characters from a unix data file.Here is my data looks as below.

First 12 characters is column 1 and next 10 characters is 2nd column.

000000000001199998000180000     DUMMY RAG #         MFR NOT ST            1999980    ZZ-            0        0              0ZZ-
000000000002199998000180000     DUMMY RAG #         MFR NOT ST            1999980    ZZ-            0        0              0ZZ-
000000000003199998000180000     DUMMY RAG #         MFR NOT ST            1999980    ZZ-            0        0              0ZZ-
000000000004199998000180000     DUMMY RAG #         MFR NOT ST            1999980    ZZ-            0        0              0ZZ-
000000000005199998000180000     DUMMY RAG #         MFR NOT ST            1999980    ZZ-            0        0              0ZZ-
000000000006199998000180000     DUMMY RAG #         MFR NOT ST            1999980    ZZ-            0        0              0ZZ-

Answer

Chris Seymour picture Chris Seymour · Jan 22, 2013

With cut:

$ cut -c-22 file
0000000000011999980001
0000000000021999980001
0000000000031999980001
0000000000041999980001
0000000000051999980001
0000000000061999980001

If I understand the second requirement you want to split the first 22 characters into two columns of length 10 and 12. sed is the best choice for this:

$ sed -r 's/(.{10})(.{12}).*/\1 \2/' file
0000000000 011999980001
0000000000 021999980001
0000000000 031999980001
0000000000 041999980001
0000000000 051999980001
0000000000 061999980001