Concat String with variable after a 'grep' and awk

Here is the structure of my file:
MyFile.txt

    g-4.n.g.fr 10.147.243.63 g-4.n.g.fr-w1

Here is my sript:

test.sh

 #! /bin/sh
 ip=10.147.243.63
 worker=$(grep -e $ip $1 | awk '{ print $3; }')
 echo "[Hostname: ]"
 echo $worker
 echo "[Before concat]"
 echo $worker
 echo "[After concat]"
 echo "$worker.v.1"

 echo "*****************************************************"
 ip=10.147.243.63
 worker="abcd"
 echo "[Hostname: ]"
 echo $worker
 echo "[Before concat]"
 echo $worker
 echo "[After concat]"
 echo "$worker.v.1"

./test.sh MyFile.txt
I have this output:

 [Hostname: ]
g-4.n.g.fr-w1
[Before concat]
g-4.n.g.fr-w1
[After concat]
.v.1n.g.fr-w1
*****************************************************
[Hostname: ]
abcd
[Before concat]
abcd
[After concat]
abcd.v.1

Please, why i have wrong concatenation in the first case ?

awk --version
GNU Awk 4.0.1

echo $SHELL
/bin/bash

Thank you so much for help.
Kind Reagrds.

There are probably carriage return (windows) characters in your input file.
Convert your file to UNIX format first:

tr -d '\r' < MyFile.txt > MyNewFile.txt
2 Likes

Really, thank you so much for help.
it works now.

Please, can you explain me more why i have to convert to UNIX format ? Is there a hidden characters ?

Kind regards.

You're welcome..

You need to convert to Unix format, because you are on a Unix/Linux OS. I doubt that it would work on that other machine if your would use the same input file there (with the carriage return characters).

The carriage return characters are usually there because a file originated on Windows platform and was transferred to Unix without properly converting first...

You are right. it works on the other machine because i have done a copy/paste of the content of DetailsWorkers.txt and not scp the file.

But,

i haven't used windows platform at all. The file DetailsWorkers.txt is generated by a script shell on linux
i think that there is a hidden charactar in the file DetailsWorkers.txt!!! not ?
Bests

Then have a look at that shell script and see if it explicitly inserts them into the output.
Or... if that shell script itself uses another input file that happens to contain carriage returns, then they may stem from there...

1 Like

Awk, seldom, would require the help of grep to filter, and this is not one

worker=$(grep -e $ip $1 | awk '{ print $3; }')

This saves piping into it.

worker=$(awk -v IP=$ip '$2 ~ IP {print $3}' $1)

And in awk you can do an even more precise match with

worker=$(awk -v IP=$ip '$2==IP {print $3}' $1)