Hello,
Thank you for confirming that - I've now moved this thread to the "Homework & Coursework Questions" topic. So: there are many ways of doing this, but one method that a lot of people tend to choose in these situations is to use the awk
command. One of the things awk
can do quite easily and quickly is pick out parts of its input and print them in whatever format is desired as its output. It can do a lot more than that as it happens - it's an entire programming language all to itself - but this is definitely one of the most common tasks for which it's typically used.
So, I'd encourage you to search for previous threads here on this forum regarding printing multiple columns with awk
, as this is a topic that has come up a great deal over the years. I'll give you a few quick examples however.
Imagine we have the following input file:
$ cat fruits.txt
apple orange strawberry banana
raspberry blackberry kiwi tangerine
blueberry lemon grapefruit melon
$
Now, let's say we want to print the second field of each line in this file. We can do that easily with awk
as follows:
$ awk '{print $2}' fruits.txt
orange
blackberry
lemon
$
Now let's imagine we've been asked to print the first and fourth fields, with a space between them. Here's how we do that:
$ awk '{print $1,$4}' fruits.txt
apple banana
raspberry tangerine
blueberry melon
$
Lastly, let's see how we add a bit more formatting to our output. Let's say we've been asked to print a report stating "The first fruit on this line is X" for the first fruit on each line. Here's how we do that:
$ awk '{print "The first fruit on this line is",$1}' fruits.txt
The first fruit on this line is apple
The first fruit on this line is raspberry
The first fruit on this line is blueberry
$
So, that's a quick summary of how to do the most basic kind of field selecting and output formatting with awk
.
Now, one question for you to consider and research the answer to: how do you handle printing multiple fields when they're not separated by spaces, but with commas, as they are in your input ? There must be a way to specify a different field separator - and indeed there is. Have a go, and see what you can come up with.
Hope this helps !