0

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?

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, the $author is retrieved from elsewhere author="$(echo $line | awk -F@ '{print $2}')" earlier in the script.
@Village You need to pass variables to awk. If it's a shell variable, say: -vauthor="$author" -v title="$title"
1
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

Comments

1

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  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.