首页 > 解决方案 > 如何附加文件 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

标签: sed

解决方案


您可以使用递增的 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打印发生替换的所有行。整个事情都被包装了,{}所以我们只需要重定向一次输出。


推荐阅读