sed - 如何附加文件 n 次并使用 sed 对块进行编号?
问题描述
我有一个文本文件,它有 5000 行和 3 个标题行。
把它想象成一个街区。
我想在一个新文件中复制 10 个块,删除第二个到第 10 个副本的标题,并将第一列中的块编号为 0 到 9,覆盖每行中的第一个 0。
我有一个笨拙的解决方案并寻找一种更优雅的方式。
例子:
file.txt
head1
head2
head3
0;1; 100.0;200.0;300.0...
0;2; 100.0;200.0;300.0...
0;3; 100.0;200.0;300.0...
目标:
goal.txt
head1
head2
head3
0;1; 100.0;200.0;300.0...
0;2; 100.0;200.0;300.0...
0;3; 100.0;200.0;300.0...
1;1; 100.0;200.0;300.0...
1;2; 100.0;200.0;300.0...
1;3; 100.0;200.0;300.0...
2;1; 100.0;200.0;300.0...
2;2; 100.0;200.0;300.0...
2;3; 100.0;200.0;300.0...
3;1; 100.0;200.0;300.0...
4;2; 100.0;200.0;300.0...
4;3; 100.0;200.0;300.0...
4;1; 100.0;200.0;300.0...
5;2; 100.0;200.0;300.0...
5;3; 100.0;200.0;300.0...
6;1; 100.0;200.0;300.0...
6;2; 100.0;200.0;300.0...
6;3; 100.0;200.0;300.0...
7;1; 100.0;200.0;300.0...
7;2; 100.0;200.0;300.0...
7;3; 100.0;200.0;300.0...
8;1; 100.0;200.0;300.0...
8;2; 100.0;200.0;300.0...
8;3; 100.0;200.0;300.0...
9;1; 100.0;200.0;300.0...
9;2; 100.0;200.0;300.0...
9;3; 100.0;200.0;300.0...
解决方案
sed '1,3d' file.txt > fileWithoutHeader.txt
sed 's/^0;/1;/g' fileWithoutHeader.txt > fileWithoutHeader1.txt
sed 's/^0;/2;/g' fileWithoutHeader.txt > fileWithoutHeader2.txt
sed 's/^0;/3;/g' fileWithoutHeader.txt > fileWithoutHeader3.txt
sed 's/^0;/4;/g' fileWithoutHeader.txt > fileWithoutHeader4.txt
sed 's/^0;/5;/g' fileWithoutHeader.txt > fileWithoutHeader5.txt
sed 's/^0;/6;/g' fileWithoutHeader.txt > fileWithoutHeader6.txt
sed 's/^0;/7;/g' fileWithoutHeader.txt > fileWithoutHeader7.txt
sed 's/^0;/8;/g' fileWithoutHeader.txt > fileWithoutHeader8.txt
sed 's/^0;/9;/g' fileWithoutHeader.txt > fileWithoutHeader9.txt
cat file.txt > goal.txt
cat fileWithoutHeader1.txt>> goal.txt
cat fileWithoutHeader2.txt>> goal.txt
cat fileWithoutHeader3.txt>> goal.txt
cat fileWithoutHeader4.txt>> goal.txt
cat fileWithoutHeader5.txt>> goal.txt
cat fileWithoutHeader6.txt>> goal.txt
cat fileWithoutHeader7.txt>> goal.txt
cat fileWithoutHeader8.txt>> goal.txt
cat fileWithoutHeader9.txt>> goal.txt
解决方案
您可以使用递增的 shell 参数:
{
cat file.txt
for i in {0..9}; do
sed -n "s/^0;/$i;/p" file.txt
done
} > goal.txt
sed的-n
参数禁止输出,命令的p
标志s
打印发生替换的所有行。整个事情都被包装了,{}
所以我们只需要重定向一次输出。
推荐阅读
- r - 如何在 dplyr 中使用 lapply
- apache - 删除共享主机中的 cPanel 配置路径
- javascript - 为什么 innerHTML 不能通过 AJAX 处理响应文本中的 Html 元素?
- java - java.util.Random 使计算速度提高 100 倍?
- javascript - findKey() - 重新创建 lodash 库方法
- angular - Angular Material 设计实现过滤器服务器端
- java - 可以通过@MethodSource(junit 5.1)传递多维数组吗?
- javascript - 如何在 Angular js 中打开引导日期选择器?
- ubuntu - 在 Linux 的 Windows 子系统中运行的 Ubuntu 上最大的 LMDB 映射大小
- c# - 接口属性继承