Mayank Jain
Mayank Jain

Reputation: 2564

Issue while processing a line using awk in unix

I am running realpath command on each line of a file. Two sample lines of file are

$HOME:1:2
$HOME:1:2 3

I am expecting output of above two lines after running my command as:

/home/mjain8:1:2
/home/mjain8:1:2 3

The awk command I am running is awk 'BEGIN{cmd="realpath "}{cmd$0|getline;print $0;}' FS=':' OFS=':'

Now, when I run the command on first line it runs fine and gives me the desired output. But for line 2 of file (shown above) the output is /home/mjain8:1:2 (and NOT /home/mjain8:1:2 3). That is the output only contains line before space.

Can someone please point what am I doing wrong. Also, in case you have suggestion to use any other command please let me know same too. I have been struggling to do same using awk since last 2 days.

I want to make it portable so that it run on as many shells as possible.

Upvotes: 0

Views: 78

Answers (2)

stack0114106
stack0114106

Reputation: 8711

With Perl-one liner also, you could do it easily

> export HOME=/home/mjain8
> cat home.txt
$HOME:1:2
$HOME:1:2 3
>  perl -F: -lane ' {$F[0]=$ENV{HOME} ;print join(":",@F)  } ' home.txt
/home/mjain8:1:2
/home/mjain8:1:2 3
> perl -F: -lane ' {$F[0]=$ENV{HOME} if $F[0]=~/\$HOME/;print join(":",@F)  } ' home.txt # if you need to explicity check if it is HOME
/home/mjain8:1:2
/home/mjain8:1:2 3
>

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133650

With shell's while loop it will be much simpler, could you please try following. It worked fine for me.

while IFS=':' read -r path rest
do
   real=$(realpath "$path")
   echo "$real:$rest"
done < "Input_file"

Above code has real variable to first have realpath command's value and then it prints its output along with rest variable, in case you want to directly print them as per tripleee's comment use following then.

while IFS=':' read -r path rest
do
   echo "$(realpath "$path"):$rest"
done < "Input_file"

Upvotes: 2

Related Questions