genderbee
genderbee

Reputation: 213

Bash, awk, two arguments for one column

Need 2 arguments in awk command for one column.

Script, name todo.

#!/bin/bash

folder_main="$( cd $( dirname "${BASH_SOURCE[0]}" ) >/dev/null 2>&1 && pwd )"

if [ $1 = 'e' ]; then
    mcedit $folder_main/kb/todo.kb
else
    awk -F ',' '$1=="'$1'"' $folder_main/kb/todo.kb
fi

Expectation is when I write todo i, it will grep me lines with i OR c by the first column divided by ,.

I tried this.

    awk -F ',' '$1=="{c|'$1'}"' $folder_main/kb/todo.kb

But nothing.

Thanks.

Upvotes: 1

Views: 68

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74685

You should pass your shell variable to awk using -v and fix your awk syntax:

awk -F, -v a="$1" '$1 == "c" || $1 == a' "$folder_main/kb/todo.kb"

This sets the awk variable a to the value of the shell positional parameter $1, and prints the line if the first column is either "c" or whatever you passed as the first argument to the script.

You could also shorten the line slightly by using a regular expression match instead of two ==:

awk -F, -v a="$1" '$1 ~ "^(c|"a")$"' "$folder_main/kb/todo.kb"

Although I think that the first option is easier to read, personally. It is also safer to use, as a character with special meaning inside a regular expression (such as *, [, ( or {) could cause the script to either fail or behave in an unexpected way.

Upvotes: 2

JNevill
JNevill

Reputation: 50200

You can't use shell variables directly in awk like this. Instead you pass them into your awk script using the -v flag:

awk -F ',' -v searchterm=$1 '$1==searchterm' $folder_main/kb/todo.kb

Upvotes: 0

Related Questions