我有一个数据文件和一个包含位置列表的文件,我想从数据文件的 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/