1

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.

1
  • Ok. Now remove your mail address. Commented Sep 6, 2019 at 9:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

OK, but my first example works ok too. But your solution is more elegant. And what about 2 searchterms with OR? I tried searchterm={"$1"|"c"}, but false. Thanks.
Take a look at the other answer. That does similar to what I've done but performs the search using regex which is more elegant for your OR requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.