Home > Software design >  Local vs Supplied Shell Script Arguments
Local vs Supplied Shell Script Arguments

Time:11-21

Writing a shell script that receives 3 arguments but within the script one of the commands needs to check the first value after a delimiter is applied

#!/bin/bash
awk -F'\t' '$1 ~ /$1/&&/$2/ {print $1FS$3}' $3

this command is called:

bash search.sh 5 AM filename.txt

And should execute as follows:

awk -F'\t' '$1 ~ /5/&&/AM/ {print $1FS$3}' filename.txt

The command functions properly outside of the shell script, returns nothing right now when using it inside the shell script. filename.txt :

03:00:00 AM John-James Hayward  Evalyn Howell   Chyna Mercado
04:00:00 AM Chyna Mercado   Cleveland Hanna Katey Bean
05:00:00 AM Katey Bean  Billy Jones Evalyn Howell
06:00:00 AM Evalyn Howell   Saima Mcdermott Cleveland Hanna
07:00:00 AM Cleveland Hanna Abigale Rich    Billy Jones

Expected output:

05:00:00 AM Billy Jones

CodePudding user response:

Your arguments are not being expanded when you single quote them. Here double quoting what you want the shell to expand, and single quote what you want awk to see:

#!/bin/bash
awk -F'\t' "$1 ~ /$1/&&/$2/"' {print $1FS$3}' "$3"

and to @JohnKugelman's point of using awk variables to more clearly separate shell and awk code:

#!/bin/bash
awk -F'\t' -vp="$1" -vp2="$2" '($0 ~ p && $0 ~ p2) {print $1FS$3}' "$3"

I use generic variable names here (p and p2) to emphasize that you are not anchoring your regex so they really do match on the hole line instead of hour and am/pm as intended.

CodePudding user response:

Don't embed shell variables in an awk script.

Here's a solution with some explanatory comments:

#!/bin/bash

[[ $# -lt 2 ]] && exit 1       ## two args required, plus files or piped/redirected input

hour="$(printf 'd' "$1")"   ## add a leading zero if neccesary
pm=${2^^}                      ## capitalise

shift 2

time="^$hour:.* $pm\$"         ## match the whole time field

awk -F '\t' -v time="$time" \
'$1 ~ time {print $1,$3}' "$@" ## if it matches, print fields 1 and 3 (date, second name)

Usage is bash search.bash HOUR PM [FILE] ..., or ./search HOUR PM [FILE] ... if you make it executable. For example ./search 5 am file.txt or ./search 05 AM file.txt.

I'm assuming that every field is delimited by tabs.

  • Related