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-
To access the first n characters of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction. length: The number of characters we need to extract from a string.
Using the head Command The head command is used to display the first lines of a file. By default, the head command will print only the first 10 lines. The head command ships with the coreutils package, which might be already installed on our machine.
To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>. By default, head shows you the first 10 lines of a file. You can change this by typing head -number filename, where number is the number of lines you want to see.
head command is a command-line utility, which prints the first 10 lines of the specified files. If more than one file name is provided then data from each file is preceded by its file name. We can change the number of lines the head command prints by using the -n command line option.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With