gpt4 book ai didi

linux - Bash 将大文件拆分为较小的文件

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:15 26 4
gpt4 key购买 nike

所以我想根据第 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' 相邻" 的计算结果为 "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

并与经典 Bourne shell 兼容。)

关于linux - Bash 将大文件拆分为较小的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15980111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com