1847253 Members
4414 Online
110263 Solutions
New Discussion

awk problem

 
Declan Heerey
Frequent Advisor

awk problem

I am reading a file which sometimes has two positional parameters but sometimes it has more. I.e..

File.txt

/Home/temp/user /Thisismyhome/
/Home/temp/newuser /Thisismyhome/
/Home/temp/bob /Thisismyhome and something/

When I print $1,$2 I get

/Home/temp/user /Thisismyhome/
/Home/temp/newuser /Thisismyhome/
/Home/temp/bob /Thisismyhome


But I need to include the “and something/” from the last line i.e. $3 and $4

So I want to print something like $1, $2* (the star being to the end of the line)

Anybody got any ideas?

All help appreciated

Declan

6 REPLIES 6
Peter Godron
Honored Contributor

Re: awk problem

Declan,
until you get your awk solution:

#!/usr/bin/sh
while read dat1 dat2
do
echo $dat1
echo $dat2
done < datafile

dat1 = Data to first space
dat2 = All other data to end of line

If you add dat3 to the read line:
dat1 = Data to first space
dat2 = Data from end of dat1 to second space
dat3 = All other data to end of line
spex
Honored Contributor

Re: awk problem

Hi Declan,

How about:

# awk -F' /' '{print $1,$2}' File.txt

PCS
Hein van den Heuvel
Honored Contributor

Re: awk problem

Just print $0 ?

Remember, you can also set NF.
So you can do: awk '{NF=4; print}' x.txt

Just keep on printing?
awk '{print $1,$2,$3,$4}

Count, using printf to avoid new-line?

awk '{for (i=1; i

So many ways, the best one depends on the exact problem to solve.

hth,
Hein.
Peter Godron
Honored Contributor

Re: awk problem

Declan,
and my awk solution:
awk '{print $1,$2=substr($0,length($1)+1)}' datafile

Which prints the first field and then works out the string to print for field to by taking the whole line ($0) and moving the start point to print just past the length of the first field. The end point is the end of the line.

Declan Heerey
Frequent Advisor

Re: awk problem

Thanks for all the replies, i'm going to test each one now and will update the thread when i've finished (and i'll assign points)

Thanks again

Declan
Declan Heerey
Frequent Advisor

Re: awk problem

Wey hey thanks to all, as you can guess they all work in there own right but the variation i have used is based on Peter's reply

awk '{print$2=substr($0,length($1)+1)}' datafile.txt

Thanks again to everyone

Regards

Declan