开发者

How to properly parse this scenario in a simple bash script?

I have a file where each key-value pair takes a new line. There is a possibility of having multiple values for each key. I want to return开发者_如何学C a list of all pairs that have a "special key", where "special" is is defined as some function.

For Example, if "special" is defined as a key that somewhere has a value of 100

A 100
B 400
A hello
B world
C 100

I would return

A 100
A hello
C 100

How to do this in bash?


#!/bin/bash

special=100    

awk -v s=$special '
{
  a[$1,$2]
  if($2 ~ s)
    k[$1]
}

END
{
  for(key in k)
    for(pair in a)
    {
      split(pair,b,SUBSEP)
        if(b[1] == key)
          print b[1],b[2]
    }
}' ./infile

Proof of Concept

$ special=100; echo -e "A 100\nB 400\nA hello\nB world\nC 100" | awk -v s=$special '{a[$1,$2];if($2 ~ s)k[$1]}END{for(key in k)for(pair in a){split(pair,b,SUBSEP); if(b[1] == key)print b[1],b[2]}}'
A hello
A 100
C 100


This would also work:

id=`grep "\<$special\>$" yourfile | sed -e "s/$special//"`
[ -z "$id" ] || grep "^$id" yourfile

Returns:

If special=100

A 100
A hello
C 100

If special="hello"

A 100
A hello

If special="A"

(nothing)

If special="ello"

(nothing)

Notes

  • drop the \<\> if you want partial match
  • add | uniq at the end if there is a possibility of multiple entrances of the same pair (A 100, A 100, ...) but you don't want that in your output.


***** script *****

#!/bin/bash

grep " $1" data.txt | cut -d ' ' -f1 | grep -f /dev/fd/0 data.txt

result:

./test.sh 100

A 100
A hello
C 100

***** inline *****

the first grep must contain the 'special' preceded by a space ' ':

grep " 100" data.txt | cut -d ' ' -f1 | grep -f /dev/fd/0 data.txt

A 100
A hello
C 100


awk -v special="100" '$2==special{a[$1]}($1 in a)' file


Whew! My bash was incredibly rusty! Hope this helps:

FILE=$1
IFS=$'\n' # Internal File Sep, so as to avoid splitting in whitespaces
FIND="100"
KEEP=""

for line in `cat $FILE`; do
    key=`echo $line | cut -d \  -f1`;
    value=`echo $line | cut -d \  -f2`;

    echo "$key = $value"

    if [ "$value" == "$FIND" ]; then
            KEEP="$key $KEEP"
    fi
done

echo "Keys to keep: $KEEP"

# You can now do whatever you want with those keys.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜