Jason Perry
Jason Perry

Reputation: 13

Store String var in awk command

I have txt file like this:

Dupont Charles
Martin Paul
Dupuis Jean

I want, for each line, to make a login corresponding to first 2 caracters of each names. For instance : Dupont Charles ==> duch

awk '{print tolower(substr($1,1,1)substr($2,1,1))}' liste.txt

works perfectly.

but i want to store each login in var and call a bash script (uscript) with that var...

awk '{login=tolower(substr($1,1,1)substr($2,1,1));print $login; script1 $login; }' liste.txt

But it does not work and the content of login is not what I want.

Upvotes: 1

Views: 105

Answers (2)

Ed Morton
Ed Morton

Reputation: 203189

awk '{print tolower(substr($1,1,2)substr($2,1,2))}' liste.txt | xargs script1

e.g. using echo instead of script1 which of course I don't have:

$ awk '{print tolower(substr($1,1,2)substr($2,1,2))}' liste.txt | xargs echo
duch mapa duje

or if script1 requires 1 arg at a time:

awk '{print tolower(substr($1,1,2)substr($2,1,2))}' liste.txt | xargs -n1 script1

e.g.

$ awk '{print tolower(substr($1,1,2)substr($2,1,2))}' liste.txt | xargs -n1 echo
duch
mapa
duje

Upvotes: 1

fedorqui
fedorqui

Reputation: 289505

The way to use variables in awk is different from Bash. In awk, a variable does not have a leading $. So what you want to say is:

awk '{login=tolower(substr($1,1,1)substr($2,1,1));print login; }' liste.txt
#                                                       ^
#                                                 intead of $login

However, you are willing to use a script script1 with this value. For this, you may want to use system() to call an external command............... or use a while block to handle all in one.

while IFS= read -r name surname
do
    login=${name:0:2}${surname:0:2}
    script1 "$login"  
done < file

This uses the same logic to get the 3 first characters of a variable:

$ v="123456789"
$ echo ${v:0:3}
123

Upvotes: 2

Related Questions