簡體   English   中英

如何將一個文本文件逐行拆分為兩個按定界符分隔的文本文件?

[英]How can I split a text file line by line into 2 text files by delimited column?

我嘗試了以下各種組合:

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
awk -F' \\|\\|\\| ?' '{print $1 > "column1"; print $2 > "column2"}' file

或更一般地

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

你可以試試

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標志會將定界符一起壓縮。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM