You should be doing that in a single call to awk, not calling awk repeatedly in a shell loop as that'll be extremely slow and is hard to write the code robustly. If you post some concise, testable sample input and expected output then we can help you more but it sounds like this might be what you're trying to do:
awk -v vars="$variable1\t$variable2\t$variable3" '
BEGIN { OFS="\t" }
NR>5 { print vars, prev }
{ prev = $2 }
' Table1.txt > Table2.csv
For example:
$ variable1='this stuff'
$ variable2='other stuff'
$ variable3='last stuff'
$ cat Table1.txt
01 the foo
02 quick bar
03 brown foo
04 fox bar
05 jumped foo
06 over bar
07 the foo
08 lazy bar
09 dogs foo
10 back bar
$ awk -v vars="$variable1\t$variable2\t$variable3" '
BEGIN { OFS="\t" }
NR>5 { print vars, prev }
{ prev = $2 }
' Table1.txt > Table2.csv
$ cat Table2.csv
this stuff other stuff last stuff jumped
this stuff other stuff last stuff over
this stuff other stuff last stuff the
this stuff other stuff last stuff lazy
this stuff other stuff last stuff dogs
If any of those $variable
s can contain escape sequences that you don't want expanded (e.g. \t
to a literal tab char), then do this instead:
vars="$variable1"$'\t'"$variable2"$'\t'"$variable3" awk '
BEGIN { vars=ENVIRON["vars"]; OFS="\t" }
NR>5 { print vars, prev }
{ prev = $2 }
' Table1.txt > Table2.csv
See how-do-i-use-shell-variables-in-an-awk-script for more information on how to pass the value of shell variables to an awk script.
To address that echo $word
in your shell script. If that's a debugging print then it should really go to stderr instead of stdout (i.e. it should have been written as echo "$word" >&2
) and then your awk script would be:
$ awk -v vars="$variable1\t$variable2\t$variable3" '
BEGIN { OFS="\t" }
NR>5 {
print prev | "cat>&2" # or print prev > "/dev/stderr" if your awk supports that
print vars, prev
}
{ prev = $2 }
' Table1.txt > Table2.csv
but if you REALLY want it to go to stdout then you could do this:
$ awk -v vars="$variable1\t$variable2\t$variable3" '
BEGIN { OFS="\t" }
NR>5 {
print prev
print vars, prev > "Table2.csv"
}
{ prev = $2 }
' Table1.txt
or:
$ awk -v vars="$variable1\t$variable2\t$variable3" '
BEGIN { OFS="\t" }
NR>5 {
print prev
print vars, prev | "cat>&3"
}
{ prev = $2 }
' Table1.txt 3> "Table2.csv"
$variable
s (especially if they can contain escape sequences like\t
) as well as the contents ofTable1.txt
andTable2.csv
– Ed Morton Jul 18 '21 at 12:31