How to use tab separators with grep in ash or dash script?

274 views Asked by At

Task at hand:

I have a file with four tab separated values:

peter 123   five   apples
jane  1234  four   rubberducks
jimmy 01234 seven  nicknames

I need to get a line out of this file based on second column, and the value is in a variable. Let's assume I have number 123 stored in a variable foo. In bash I can do

grep $'\s'$foo$'\s'

and I get out of peter's info and nothing else. Is there a way to achieve the same on dash or ash?

2

There are 2 answers

6
anubhava On BEST ANSWER

You can use awk here:

var='1234'
awk -v var="$var" '$2 == var ""' f
jane  1234  four   rubberducks

PS: I am doing var "" to make sure var is treated as a string instead of as a number.

0
Charles Duffy On

If your file is small enough that the inefficiency of doing iteration in a shell doesn't matter, you don't actually need grep for this at all. The following is valid in any POSIX-compliant shell, including ash or dash:

var=123
while read -r first second rest; do
  if [ "$second" = "$var" ]; then
    printf '%s\t' "$first" "$second"; printf '%s\n' "$rest"
  fi
done

(In practice, I'd probably use awk here; consider the demonstration just that).