0

This is my simple script

#!/bin/bash
echo $(awk '$2 ~ /$1/ {print $0}' numeri-telefonici.txt | cut -d' ' -f1)

and numeri-telefonici.txt file is

00000 Alessandro
11312 Mark

unfortunately when I execute this script (./script.sh Alessandro) an empty row is print: , but If i execute awk '$2 ~ /Alessandro/ {print $0}' numeri-telefonici.txt | cut -d' ' -f1 I get successfully 00000.

  • How do I fix?
Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    Welcome to SO, thanks for showing your efforts in your question, keep it up. Could you please what you are trying o achieve by script? Do you want to pass an argument to awk program and compare 2nd field of your file to it? – RavinderSingh13 Nov 08 '20 at 11:23

1 Answers1

2

$1, $2 are positional parameters in the shell context that are passed to a script from command line or to a function.

In Awk, they represent column designators defined by the FS. In your attempt, you are basically only using the awk's designators, i.e. your match is doing

/Alessandro/ ~ 00000 
#  $2        ~   $1

You need to pass the positional argument to the context of awk, by importing them as awk variables using -v

awk -v re="$1" ' $2 ~ re { print $1 }'

Note the usage of print $1 instead of $0, as your operation to later use cut to get the first field is unnecessary as you can get the first column value directly from $1

Inian
  • 80,270
  • 14
  • 142
  • 161