Linux 如何获取unix数据文件中的前n个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14462529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get first n characters in unix data file
提问by Teja
I am trying to get the first 22 characters from a unix data file.Here is my data looks as below.
我正在尝试从 unix 数据文件中获取前 22 个字符。这是我的数据如下所示。
First 12 characters is column 1 and next 10 characters is 2nd column.
前 12 个字符是第 1 列,接下来的 10 个字符是第 2 列。
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-
采纳答案by Chris Seymour
With cut
:
与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:
如果我理解第二个要求,您想将前 22 个字符分成两列,长度分别为 10 和 12。这sed
是最好的选择:
$ sed -r 's/(.{10})(.{12}).*/ /' file
0000000000 011999980001
0000000000 021999980001
0000000000 031999980001
0000000000 041999980001
0000000000 051999980001
0000000000 061999980001
回答by Kent
sudo_O has provided nice cut and sed solution, I just added an awk one-liner:
sudo_O 提供了很好的 cut 和 sed 解决方案,我只是添加了一个 awk one-liner:
awk 'BEGIN{FIELDWIDTHS="22"} {print }' file
echo "000000000001199998000180000 DUMMY RAG"|awk 'BEGIN{FIELDWIDTHS="22"} {print }'
0000000000011999980001
with empty char (it depends on your requirement, you want to skip the spaces or you want to include and count them in your output)
带有空字符(这取决于您的要求,您想跳过空格,或者您想在输出中包含并计算它们)
if blank spaces should be counted and displayed in output as well: (you don't have to change the cmd above)
如果空格也应计算并显示在输出中:(您不必更改上面的 cmd)
echo "0 0 0 0 00000001199998000180000"|awk 'BEGIN{FIELDWIDTHS="22"} {print }'
0 0 0 0 00000001199998
if you want to skip those spaces: (quick and dirty)
如果你想跳过这些空格:(又快又脏)
echo "0 0 0 0 00000001199998000180000"|sed 's/ //g'|awk 'BEGIN{FIELDWIDTHS="22"} {print }'
0000000000011999980001