file=$2
isHeader=$true
while read -r line;
do
if [ $isHeader ]
then
sed "1i$line",\"BATCH_ID\"\n >> $file
else
sed "$line,1"\a >> $file
fi
isHeader=$false
done < $1
echo $file
在第一行中,我想要附加一个字符串,而对于其他行,我想为其余行追加相同的字符串。我试过这个,但它不起作用。我没有任何想法,有人可以帮助我吗?
答案 0 :(得分:0)
我不完全清楚您想要做什么,但如果您只是想在每行的末尾添加文字,请使用 echo
sed
的地方:
file=$2
isHeader=1
while read -r line;
do
if [ $isHeader ]
then
#sed "1i$line",\"BATCH_ID\"\n >> $file
echo "${line},\"BATCH_ID\"\n" > $file
else
#sed "$line,1"\a >> $file
echo "${line},1\a" >> $file
fi
isHeader=0
done < $1
cat $file
答案 1 :(得分:0)
接受的答案有点不对,因为\a
... #! /bin/sh
script='NR == 1 { print $0 ",\"BATCH_ID\"" }
NR > 1 { print $0 ",1" }'
awk "$script" $1 > $2
会产生铃声。此外, awk 或 sed 支持正则表达式,并且逐行处理速度提高了10倍。这是awk:
sed '1 s/$/,"BATCH_ID"/; 2,$ s/$/,1/' $1 > $2
在sed中它甚至更简单:
$ time seq 100000 | while read f; do echo ${f}foo; done > /dev/null
real 0m2.068s
user 0m1.708s
sys 0m0.364s
$ time seq 100000 | sed 's/$/foo/' > /dev/null
real 0m0.166s
user 0m0.156s
sys 0m0.017s
为了说服自己速度,请亲自尝试:
{{1}}