所以我想根据第 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 兼容。)
我是一名优秀的程序员,十分优秀!