繁体   English   中英

如何在shell脚本中不生成临时文件的情况下在生成的文件之前附加行数

[英]How to append the number of line in front of the generated file in shell script without producing a temp file

我有一个程序来生成这样的文件:

./program1 $parameter > tempfile
lineNum=`wc -l tempfile | awk '{print $1}'`
echo $lineNum > myfile
cat tempfile >> myfile
rm -f tempfile

我想知道是否有一种方法可以在不生成“ tempfile”的情况下进行存档? 我认为我的方法有些多余,希望会有更好的方法。

你可以用这个

sed -i "1i$(wc -l myfile | cut -d' ' -f1)" myfile

(要么)

sed -i "1i$(wc -l < myfile )" myfile

例如:

./program1 $parameter > myfile
sed -i "1i$(wc -l myfile | cut -d' ' -f1)" myfile

其他解决方案:使用nl 这是一种专门用于执行此操作的工具。

./program1 $parameter | nl -w1 > myfile

在这里, -w1用于指定行号,以1个制表符分隔

输出:

1    something
2    somethingelse
3
4    and now for something completly different

如果您不想将tab用作分隔符,请使用-s"X"标志,其中X是您想要的分隔符(1个空格,2个空格,一个字母,...)。 ./program1 $parameter | nl -w1 -s" " > myfile ./program1 $parameter | nl -w1 -s" " > myfile将产生:

1 something
2 somethingelse
3
4 and now for something completly different

这并不是真的没有使用临时文件(如sed -i会为您完成),但是...

#!/bin/bash
count=$(./program1 $parameter | tee outputfile | wc -l)
sed -i 1i${count} outputfile

这可能具有不需要将整个文件加载到内存中的优势。 根据您的数据文件,这可能是问题,也可能不是问题。

您可以只使用awk

./program1 "$parameter" | awk '{lines[++n]=$0}END{print n;for(i=1;i<=n;++i)print lines[i]}' > myfile

例:

seq --format='Inline Text %.0f' 1 10 | awk '{lines[++n]=$0}END{print n;for(i=1;i<=n;++i)print lines[i]}'

输出:

10
Inline Text 1
Inline Text 2
Inline Text 3
Inline Text 4
Inline Text 5
Inline Text 6
Inline Text 7
Inline Text 8
Inline Text 9
Inline Text 10

为了好玩-并假设您的文件足够小以至于不超过可用内存-您可以仅使用bash内部执行该任务:

#!/bin/bash

# ...

./program1 $parameter |
    ( mapfile arr; echo ${#arr[@]}; IFS=""; echo -n "${arr[*]}" )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM