Operating System - HP-UX
1762466 Members
3215 Online
108907 Solutions
New Discussion юеВ

Re: Simple Shell Script problem

 
Marcus Antonius
Occasional Contributor

Simple Shell Script problem

I am trying to read a file that has two columns of data in it. The data is related horizontally.

I need to build a command using the values from each columns. For example:
My file looks like this:

Data1 Data2
Data3 Data4
Data5 Data6


I need to create a command that looks like this:

Dosomething Data1,Data2

My problem is my script simply reads the whol column and attempts to put it all on the command line.


Any help will be appreciated.


Marcus
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: Simple Shell Script problem

Hi Marcus:

This is one option:

# cat ./reformat
#!/usr/bin/sh
while read X Y Z
do
echo "somecommand ${X},${Y}"
done < inputfile

# cat ./inputfile
Data1 Data2
Data3 Data4
Data5 Data6

# ./reformat
somecommand Data1,Data2
somecommand Data3,Data4
somecommand Data5,Data6

Regards!

...JRF...
Marcus Antonius
Occasional Contributor

Re: Simple Shell Script problem

James,


Thanks for the quick response! Your solution has got me almost there. I left a small detail out of my original post.

I need two things:

1. The data columns in the file are reversed for the command I am trying to build for example:
I the file the data is arranged as below:
Data1 Data2
Data3 Data4
etc . . .

However my command requires the data be arranged with column 2's data first and then column 1. For example:

somecommand Data2,Data1
somecommand Data4,Data3
somecommand Data6,Data5 etc. . .


Also the final command requires some quotation marks for example: somecommand "Data2","Data1" etc . . .



Thanks!

Marcus.



James R. Ferguson
Acclaimed Contributor

Re: Simple Shell Script problem

Hi Marcus:

OK, according to your new requirements, simply do:

# cat ./reformat
#!/usr/bin/sh
while read X Y Z
do
echo "somecommand \"${Y}\",\"${X}\""
done < inputfile

...which produces:

somecommand "Data2","Data1"
somecommand "Data4","Data3"
somecommand "Data6","Data5"

Regards!

...JRF...
Marcus Antonius
Occasional Contributor

Re: Simple Shell Script problem

That worked!

Many Thanks!


Marcus.
Basheer_2
Trusted Contributor

Re: Simple Shell Script problem

if you like awk

awk '{print "Dosomething", $1, "," $2}' yourfile