linux - 用于从另一个文件的 block 组成文件的 shell 命令

标签 linux bash shell unix scripting

我有一个数据文件和一个包含位置列表的文件,我想从数据文件的 block 中生成一个文件。示例:

$ cat data
abcdefghijkl
$ cat positions
0,2
5,8
$ cutter positions data
abcfghi

有没有像我假设的“切割机”一样工作的 (linux) shell 命令? “positions”的特定格式并不重要。 我们可以假设在“positions”中指定的 block 是递增的,并且不重叠。 可能有一个额外的“切割器”模式,其中位置计算行而不是字节。

我自己可以很容易地实现这样一个程序,但我有直觉,这样的程序已经存在了。

最佳答案

仅使用 bash 从参数扩展中提取子字符串,并使用给定的 positions 文件格式:

data=$(< data)    # read the entire file into a variable
while IFS=, read start stop; do
    printf "%s" "${data:$start:((stop-start+1))}"
done < positions
echo

输出

abcfghi

如果您的数据文件跨越多行,您必须注意位置文件以考虑换行符。

此方法不需要您将数据文件读入内存:

#!/bin/bash
exec 3<data
exec 4<positions
pos=0
while IFS=, read start stop <&4; do
    ((nskip = start - pos))
    ((nkeep = stop - start + 1))
    ((pos += nskip + nkeep))
    ((nskip > 0)) && read -N $nskip <&3
    read -N $nkeep <&3
    printf "%s" "$REPLY"
done
echo

关于linux - 用于从另一个文件的 block 组成文件的 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14111700/

相关文章:

c - time() 和 gettimeofday() 返回不同的秒数

linux - 如何grep并写入新文件

linux - 返回小于给定日期的月结束日期,并在 shell 中停止于 12 个日期

bash - "echo ' hello';之间的区别ls"vs "echo ' 你好' && ls"?

bash - ack-grep 安装脚本中不熟悉的 shell 语法

ruby - 如何从 shell 运行 Ruby gem?

java应用程序在linux环境下登录失败

linux - 将 x 个文件 move 到新文件夹

linux - 如何以不同用户身份运行 bash 命令?

bash - shell脚本中的竖线?