Can't split a text file based on separator

坚强是说给别人听的谎言 提交于 2020-02-16 06:52:09

问题


I'm running Ubuntu 18.04 LTS. I have a text file named "group_keys", which contains a number of public keys that I'd like to split based on the delimiter

-----BEGIN PUBLIC KEY-----

and then output each key individually and sequentially. For example, if there are three keys, then the output would be three files with names like "person_1_key", "person_2_key", and "person_3_key".

The file looks like this:

I'm having difficulty using split and csplit to do this. The commands I'm inputting aren't working. Here's what I've tried;

Using split:

split --separator="-----BEGIN PUBLIC KEY-----" group_keys

This doesn't output anything, but instead gives me the message

split: multi-character separator ‘-----BEGIN PUBLIC KEY-----’

Using csplit:

csplit group_keys "-----BEGIN PUBLIC KEY-----"

This gives me only two files, "xx00" and "xx01", but it doesn't split the lines. "xx00" is completely blank, and the "xx01" is just the original file.


回答1:


Try

csplit -z -f person_ -b '%d_key' group_keys '/-----BEGIN PUBLIC KEY-----/' '{*}'

which would output four files person_0_key, person_1_key, person_2_key, person_3_key where

  • -z suppresses the generation of empty files
  • -f person_ sets the output filename prefix
  • -b '%d_key' sets the output filename suffix
  • '{*}' sets the repeat count (repeat as many times as possible)



回答2:


This should work:

awk '/-----BEGIN PUBLIC KEY-----?/{n++}{print > "person_" n "_key" }' group_keys



来源:https://stackoverflow.com/questions/60119372/cant-split-a-text-file-based-on-separator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!