【问题标题】:How can I split a text file line by line into 2 text files by delimited column?如何按分隔列将文本文件逐行拆分为 2 个文本文件?
【发布时间】:2017-02-22 01:06:50
【问题描述】:

我尝试了以下各种组合:

awk -F" ||| " '{$0=$1}1' source_file.txt > column1.txt
awk -F" ||| " '{$0=$1}2' source_file.txt > column2.txt

awk 'BEGIN {FS=" ||| ";}{print $1}' source_file.txt > column1.txt
awk 'BEGIN {FS=" ||| ";}{print $2}' source_file.txt > column2.txt

我要么得到整行(例如foo bar ||| baz),要么只得到第一个单词(例如foo),而不是所需的输出。

如果您愿意提供帮助,这里有一个示例文本文件:

source_file.txt

foo bar ||| baz
qux ||| quux
corge grault ||| garply waldo
fred |||
xyzzy ||| thud

这是所需的输出:

column1.txt

foo bar
qux
corge grault
fred
xyzzy

column2.txt

bar
quux
garply waldo

thud

【问题讨论】:

    标签: linux awk sed text-manipulation


    【解决方案1】:
    awk -F' \\|\\|\\| ?' '{print $1 > "column1"; print $2 > "column2"}' file
    

    或更一般地

    awk -F' \\|\\|\\| ?' '{for(i=1;i<=NF;i++) print $i > "column"i}' file
    

    【讨论】:

    • 谢谢。你也得到这个错误吗? awk: syntax error at source line 1 context is {for(i=1;i&lt;=NF;i++) print $i &gt; &gt;&gt;&gt; "column"i &lt;&lt;&lt; } awk: illegal statement at source line 1
    • 在我的情况下没有错误,请确保脚本使用单引号。
    【解决方案2】:

    你可以试试

    cat /tmp/a | tr -s '|' | cut -d'|' -f1 #for part 1
    
    cat /tmp/a | tr -s '|' | cut -d'|' -f2 | sed -E "s/^[[:space:]]+//g" #for part 2
    

    tr 标志将分隔符挤在一起。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多