bash - 在 bash 脚本中运行 awk

标签 bash unix awk

有没有办法运行 awk bash 内的脚本脚本? 我有一个大文件(~40GB),我想根据第三个字段拆分它。第三个字段可以是 chr1 , chr2 ... chr22 , chrXchrY (共24种)。当我运行时

awk 'BEGIN{OFS=FS="\t"}$3=="chr1"{print $0}' inputfile.txt > inputfile_chr1.txt

它运行良好,但当我尝试循环时却没有:

for i in {1..22} X Y; do 
awk 'BEGIN{OFS=FS="\t"}$3=="chr${i}"{print $0}' inputfile.txt > inputfile_chr${i}.txt
done

我尝试使用单引号 $3和反斜杠来转义 $3但一切都失败了。有更好的方法吗?

最佳答案

您不想使用当前的 bash 方法。您正在阅读 40GB inputfile.txt 24 次!只需使用 awk 解析一次文件即可:

awk '{file="inputfile_"$3".txt";print >> file;close(file)}' inputfile.txt 

演示:

$ ls
inputfile.txt

$ cat inputfile.txt 
1 foo chr1
2 bar chr1
3 abc chr2
4 zyz chr3
5 123 chr2

$ awk '{file="inputfile_"$3".txt";print >> file;close(file)}' inputfile.txt

$ ls
inputfile_chr1.txt  inputfile_chr2.txt  inputfile_chr3.txt  inputfile.txt

$ cat inputfile_chr1.txt 
1 foo chr1
2 bar chr1

$ cat inputfile_chr2.txt 
3 abc chr2
5 123 chr2

$ cat inputfile_chr3.txt 
4 zyz chr3

关于bash - 在 bash 脚本中运行 awk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16283564/

相关文章:

bash - 您可以访问陷阱中退出命令的代码吗?

linux - "error occurred while loading or saving configuration information"

regex - 用于替换文件中第一次出现的 sed 命令不起作用

linux - awk 在 linux 中子集化失败

linux - 在 Bash/Awk/Perl 中有效地按列计算 token

bash - 如何将非交互式参数传递到使用 "read"的 bash 文件中?

linux - 在两个模式之间添加字符串 - sed

linux - 如何使用 "sed"Bash 命令

linux - 如何将 iso 8601 转换为自 1970-01-01 00 :00:00 UTC 以来的秒数

java - Postgres 错误(设置 PLJava)