[英]How to extract text from columns and feed them to a code on Linux (bash)?
[英]How to extract values from a text file and rearrange them using Bash?
我有一個相當大的文本文件,其中包含很長的值列表。 從這個文件中,我需要提取大小、表面積和體積的值,然后將它們重新排列成標題為acorgingly 的列。
數據目前具有以下格式:
{不需要的數據列}
magnitude : 38.662 +- 0.0556 N
surface area : 31.882 +- 0.0584 m^2
volume : 545.56 +- 0.6562 m^3
{不需要的數據列}
magnitude : 38.682 +- 0.0606 N
surface area : 31.832 +- 0.0587 m^2
volume : 545.78 +- 0.6362 m^3
所需輸出:
magnitude surface area volume
38.662+-0.0556 N 31.882+-0.0584 m^2 545.56+-0.6562 m^3
38.682+-0.0606 N 31.832+-0.0587 m^2 545.78+-0.6362 m^3
我正在使用 bash 並嘗試過:
grep -e 'magnitude|surface area|volume' '{print}' original_file.txt > new_file.txt
注意我不是 Bash 腳本方面的專家。
好吧,很可能不是最優雅的解決方案,但它應該有效:
awk -F':' 'BEGIN { print "magnitude\tsurface area\tvolume" } /magnitude/,/volume/{gsub(/[ \t]+/, "", $2); printf $(2); printf " "; if (/volume/){printf "\n"}}' YOUR_FILE.txt
這產生:
magnitude surface area volume
38.662+-0.0556N 31.882+-0.0584m^2 545.56+-0.6562m^3
38.662+-0.0556N 31.882+-0.0584m^2 545.56+-0.6562m^3
輸入:
junk
junk
junk
magnitude : 38.662 +- 0.0556 N
surface area : 31.882 +- 0.0584 m^2
volume : 545.56 +- 0.6562 m^3
junk
junk
magnitude : 38.662 +- 0.0556 N
surface area : 31.882 +- 0.0584 m^2
volume : 545.56 +- 0.6562 m^3
junk
使用gawk
:
gawk -F':' 'BEGIN { print "magnitude\tsurface area\tvolume" } /magnitude/,/volume/{gsub(/[ \t]+/, "", $2); $2=gensub(/([Nm]+[23^]*)/, " \\1", "g", $(2)); printf $(2); printf " "; if (/volume/){printf "\n"}}' YOUR_FILE.txt
結果:
magnitude surface area volume
38.662+-0.0556 N 31.882+-0.0584 m^2 545.56+-0.6562 m^3
38.662+-0.0556 N 31.882+-0.0584 m^2 545.56+-0.6562 m^3
sed
讀取 3 個連續行並將列分隔符插入到輸入中並合並 3 行。column
。grep 'magnitude\|surface area\|volume' original_file.txt |
sed '
s/^magnitude *: *\([^ ]*\) \([^ ]*\) *\([^ ]* [^ ]*\) */\1\2\3/
N
s/\nsurface area *: *\([^ ]*\) \([^ ]*\) *\([^ ]* [^ ]*\) */|\1\2\3/
N
s/\nvolume *: *\([^ ]*\) \([^ ]*\) *\([^ ]* [^ ]*\) */|\1\2\3/
' |
column -t -s '|' -N 'magnitude,surface area,volume' -o ' '
對於original_file.txt
這些內容:
dfasfdasfa
magnitude : 38.662 +- 0.0556 N
surface area : 31.882 +- 0.0584 m^2
volume : 545.56 +- 0.6562 m^3
fasdfdasfafa
magnitude : 38.682 +- 0.0606 N
surface area : 31.832 +- 0.0587 m^2
volume : 545.78 +- 0.6362 m^3
fdasfdasfa
該腳本將輸出:
magnitude surface area volume
38.662+-0.0556 N 31.882+-0.0584 m^2 545.56+-0.6562 m^3
38.662+-0.0556 N 31.882+-0.0584 m^2 545.56+-0.6562 m^3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.