簡體   English   中英

Bash將大文件拆分為較小的文件

[英]Bash split large file into smaller files

所以我想根據第8列將一個相當大的文件拆分成幾個小文件。 所以我寫了這個腳本:

#!/bin/bash
run_command(){
eval ${1}
wait
}
chInput=("1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "Z" "T" "G" "F" "A" "D" "P")
sampInput=("heyA")

for ((x=0;x<${#chInput[@]};x++));do
com="awk -F'\t' '$8=="${chInput[x]}"' /home/location/"$sampInput"_This_P.txt > "$sampInput"Ch"${chInput[x]}".txt"
run_command "${com}"
done

但它不起作用因為

“$ 8 ==”

awk: ==1
awk: ^ syntax error
awk: ==2
awk: ^ syntax error
awk: ==3
awk: ^ syntax error
awk: ==4
awk: ^ syntax error

但只是這樣做

awk -F'\t' '$8==1' /home/location/heyA_This_P.txt > Ch1.txt

從命令行確實工作

我該怎么做才能解決這個問題?

急性問題是雙引號; 在分配變量時, $8將被某些東西取代(可能根本沒有)。 您可以嘗試使用單引號並進行適當的轉義,但真正的解決方案可能是深呼吸並重新開始,而無需在變量中使用eval或Awk腳本。

無論如何,這個椒鹽卷餅邏輯的目的是什么? 你應該閱讀並理解http://mywiki.wooledge.org/BashFAQ/050中的建議

以下是解決問題的快速嘗試:

#!/bin/bash

chInput=("1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "Z" "T" "G" "F" "A" "D" "P")
sampInput=("heyA")

for ((x=0;x<${#chInput[@]};x++));do
    awk -F'\t' '$8=="'"${chInput[x]}"'"' /home/location/"$sampInput"_This_P.txt > "$sampInput"Ch"${chInput[x]}".txt
done

特別注意用於在腳本中插入"${chInput[X]}"的構造(實際上,除了刪除變量和eval之外,這實際上是我唯一改變的東西)。 這是單引號中的字符串,與雙引號中的字符串相鄰,與單引號中的字符串相鄰,在Bash中計算為單個字符串。 所以'foo'"bar"'baz'foobarbaz進行評估,同樣'"foo"'"'bar'"相鄰"'bar'"評估為"foo"'bar' 這里, '$8=="'相鄰於"${chInput[x]}"鄰近於'"'的計算結果為$8=="..."其中在雙引號的東西在分配時被替換。

(你也不需要陣列;你可以這樣做

for c in "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" \
         "13" "14" "15" "16" "17" "18" "19" "Z" "T" "G" "F" \
         "A" "D" "P"
do
    awk -F'\t' '$8=="'"$c"'"' /home/location/"$sampInput"_This_P.txt > "${sampInput}Ch$c.txt"
done

並與Classic Bourne shell兼容。)

暫無
暫無

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

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