简体   繁体   English

如何在ash或破折号脚本中的grep中使用制表符分隔符?

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

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. 假设我在变量foo中存储了数字123。 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? 有没有办法在破折号或灰烬上达到相同的效果?

You can use awk here: 您可以在此处使用awk

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. PS:我正在执行var "" ,以确保var被视为字符串而不是数字。

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. 如果您的文件足够小,以至于在Shell中进行迭代的效率不重要,那么您实际上根本不需要grep The following is valid in any POSIX-compliant shell, including ash or dash: 以下内容在任何POSIX兼容的外壳程序(包括灰或破折号)中均有效:

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). (在实践中,我可能会在此处使用awk;仅考虑演示)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM