bash - 从文件中提取信息并将其作为列添加到另一个文件中

标签 bash awk sed paste

我有这个文件(test.txt):

###########
###########
1x1 1y1
1x2 1y2
###########
###########
2x1 2y1
2x2 2y2
###########
###########
3x1 3y1
3x2 3y2

1x1, 1x2, 1Y1 , 1Y2 , etc .. represent decimal , positive and negative numerical quantities

# # Correspond to text and numbers headers are values ​​that do not want to process. Each containing 9 lines that begin with numbers

or letters.

我想使用管道生成这个输出文件(output.txt):

 1x1 1y1 2x1 2y1 3x1 3y1
 1x2 1y2 2x2 2y2 3x2 3y2

尝试:(test.sh)

touch output.txt

paste -d' ' output.txt <(sed '5,12d' test.txt | sed '1,2d' | awk '{print $1" "$2}') > output.txt
paste -d' ' output.txt <(sed '9,12d' test.txt | sed '1,6d' | awk '{print $1" "$2}') > output.txt
paste -d' ' output.txt <(sed '1,10d' test.txt | awk '{print $1" "$2}') > output.txt

结果: 猫输出.txt

3x1 3y1
3x2 3y2

我的脚本做错了?

我忘了提及 test.txt 文件实际上有 1,000,000 行。因此,我想有效地做到这一点。我通过使用辅助文件解决了这个问题,但是性能非常慢。这就是为什么我想不使用辅助文件。

问候

最佳答案

paste <(grep "^1x" test.txt)  <(grep "^2x" test.txt) <(grep "^3x" test.txt)
1x1 1y1 2x1 2y1 3x1 3y1
1x2 1y2 2x2 2y2 3x2 3y2

编辑:使用它作为骨架(不需要调用paste 3次):

paste <(grep <your_regex_1> test.txt) \
      <(grep <your_regex_2> test.txt) \
      <(grep <your_regex_3> test.txt)

关于bash - 从文件中提取信息并将其作为列添加到另一个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31359584/

相关文章:

bash - 仅使用 Bash 模式匹配从字符串开头删除模式

regex - 理解 bash 脚本中的 grep 模式

shell - 如何在 sed 搜索模式中使用变量

bash - Tmux 重新加载 Bash .profile

linux - 在bash中,如何将返回值存储在变量中?

sed 和 awk : how to replace a section of file to another content?

awk 输出字段相对于长度的百分比

regex - 用其他文件中的行替换行号

bash - awk 对一列求和并在每行输入中打印该总和

unix - 如何使用 SED/AWK 交换文本文件中的第一行和最后一行