如何将BASH变量中的一些数据添加到CSV文件中所有行的开头?

时间:2014-03-15 04:57:30

标签: bash csv sed awk

我需要将$author \t $title \t添加到制表符分隔的CSV文件中每行的开头。这是文件最初的样子:

0001      This is a line.
0002      This is another line.
0003      This is yet another line.

编辑后,假设$author设置为“Lewis Carroll”并且$title设置为“透过镜子”,输出将如下所示:

Lewis Caroll      Through the Looking Glass      0001      This is a line.
Lewis Caroll      Through the Looking Glass      0002      This is another line.
Lewis Caroll      Through the Looking Glass      0003      This is yet another line.

我尝试使用awk进行了以下尝试,但它无法正常工作,$author$title似乎没有添加到文件中的任何位置:

awk -F'\t' '{ print "$author\t$title\t" $0 }' file.txt

awk -F"\t" '{ print $author \t $title \t $0 }' file.txt

如何将包含BASH变量的一些数据作为单元格添加到制表符分隔的CSV文件中所有行的开头?

3 个答案:

答案 0 :(得分:3)

不确定你是怎么做的,但它应该有效:

awk -vauthor="Lewis Carrol" -vtitle="Through the Looking Glass" '{print author, title, $0 }' OFS='\t' inputfile

您是否尝试传递shell变量?


对于手头的情况,最好不要使用sed

sed "s/^/${author}\t${title}\t/" filename

(请记住使用双引号)

答案 1 :(得分:1)

sed "s/^/${author}\t${title}\t/" file.txt

您还可以为sed添加-i选项以进行就地更新

sed -i "s/^/${author}\t${title}\t/" file.txt

答案 2 :(得分:1)

纯壳

#!/usr/bin/env ksh
author="Lewis Carrol" 
title="Through the Looking Glass" 
while read -r line
do
  printf "${author}\t${title}\t${line}\n"
done < file