Village
Village

Reputation: 24373

How to add some data from BASH variables to the beginning of all lines in a CSV file?

I need to add $author \t $title \t to the beginning of every line in a tab-seperated CSV file. This is an example of what the file looks like originally:

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

After editing, and assuming $author is set to "Lewis Carroll" and $title set to "Through the Looking Glass", the output would look just like this:

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.

I tried the following attempts with awk, but it does not work as expected, and $author and $title do not appear to be added anywhere in the file:

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

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

How can I add some data, containing BASH variables, as cells, to the beginning of all of the lines in a tab-seperated CSV file?

Upvotes: 0

Views: 68

Answers (3)

BMW
BMW

Reputation: 45223

Pure shell

#!/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  

Upvotes: 1

Amit
Amit

Reputation: 20456

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

You can also add -i option to sed for in-place update

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

Upvotes: 1

devnull
devnull

Reputation: 123458

Not sure how you're doing, but it should work:

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

Were you attempting to pass shell variables instead?


For the case at hand, you are better off using sed, though:

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

(Remember to use double quotes)

Upvotes: 3

Related Questions