分隔成分隔的空间线

2024-06-18 14:05:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我的文件包含不可预测的元素,并用空格隔开,例如:

ABC123
ABC124
ABC125  ABC321  ABC222  ABC111  ABC333
ABC069  ABC450  ABC595

我怎样才能把它们分别打印在一行呢?(python或grep/awk等)


Tags: 文件元素grep空格awkabc123abc111abc124
3条回答

使用拆分:

a = '''ABC123
ABC124
ABC125  ABC321  ABC222  ABC111  ABC333
ABC069  ABC450  ABC595'''

for item in a.split():
    print(item)

给出:

^{pr2}$

试试这个:

如果只有空间:

tr -s ' ' '\n' < file

如果您有空格和制表符,那么按照@mklement0的建议:

^{pr2}$

或者

awk '{for (i=1;i<=NF;i++) print $i}' file

或者

egrep -o 'ABC[[:digit:]]{3}' file

或者

egrep -o '[[:alnum:]]{6}' file

指令方法:

sed -E 's/\s+/\n/g' testfile

-E选项,允许扩展正则表达式


awk方法:

^{pr2}$

gsub(regexp, replacement [, target])
      Search target for all of the longest, leftmost, nonoverlapping matching substrings it can find and       replace them with replacement. The ‘g’ in gsub() stands for “global,” which means replace       everywhere.


grep方法:

grep -o '\S*' testfile

\S*-匹配所有非空白序列

相关问题 更多 >