Reputation: 131
I am trying to create an awk script to read data from a txt file and create an output script. Is it possible to create the output with awk?
while IFS=',' read -r a b c; do echo "source "$a" and target "$b" and line "$c"" ; done < test.txt
test.txt
"x","y","8"
"x","6"
"y","7"
Output:
source "x" and target "y" and line "8"
source "x" and target "6" and line
source "y" and target "7" and line
Expected Output:
"source x and target y and line 8"
"source x and line 6"
"target y and line 7"
Upvotes: 2
Views: 1087
Reputation: 203368
$ awk -F'[",]+' '{print "\"source " $2 (NF>4 ? " and target " $3 : "") " and line " $(NF-1) "\""}' file
"source x and target y and line 8"
"source x and line 6"
"source y and line 7"
Upvotes: 1
Reputation: 4455
I found it difficult to discern the requirements clearly from the provided input and output. However, if we adjust your input a bit (slightly different than Corentin's suggestion, we can provide a working awk script that provides your desired output.
Let's start with an assumption:
The input is in the following format:
<source>,<target>,<line>
Now we can write this awk script:
awk -F, '
BEGIN {
split( "source target line" , value , " " )
}
{
output=""
for ( field = 1 ; field <= length(value) ; field++ )
{
if ( $field ) {
output = output ( output ? " and " : "" ) value[ field ] " " $field
}
}
print "echo " output
}' << EOF
"x","y","8"
"x",,"6"
,"y","7"
EOF
To be honest, the above code misses the mark a little. Specifically, I didn't deal with the double quotes in the input or the output. I think that the readability of the solution would be diminished if we talked about quotes. Technically, if the quotes on the input were to protect commas (as is the case with CSV) I would consider writing this program in python (or another language) that has csv support.
Here is the output of the above program:
echo source "x" and target "y" and line "8"
echo source "x" and line "6"
echo target "y" and line "7"
Upvotes: 2