テーブルから特定のデータを抽出するにはどうすればよいですか?

テーブルから特定のデータを抽出するにはどうすればよいですか?

ここに表があります...

Group   Name            Designation
2       (John)          Front End Developer
12      (Jim)           Back End Developer
8       (Jill)          Full Stack Developer
21      (Jack)          Front End Developer
2       (James)         Front End Developer
12      (Jane)          Full Stack Developer

同じグループに属する人の名前を抽出したいです。ここで、ジョンとジェームズはグループ2に属しています。次の出力を表示するには、どのようなbashコマンドまたはスクリプト(の組み合わせ)を使用すればよいですか?

John
James

さまざまな種類の grep の組み合わせを使用しました。しかし、機能しないようです。

答え1

次のように使用できますsed:

sed -n '/^2 /s/.*(\([^)]\+\)).*/\1/p' file.txt

または、awk次のようになります。

awk -F "[()]" '/^2 / {print $2}' file.txt

最初の解決策では、行を印刷する前に括弧で囲まれた文字列に置き換えます。 2 番目の解決策では、括弧をフィールド区切り文字として使用し、フィールド 2 (括弧で囲まれた文字列) のみを印刷します。

答え2

私はこれを実行するための bash スクリプトを作成しましたが、入力としてあらゆる種類のコマンドを扱う必要があります。

スクリプトは次のとおりです。

#!/bin/bash

# Flags - to avoid potential conflicts when the labels are numbers
# 1st
# -n = only number for column
# -t = only text for column
# -a = any for column
# 2nd
# -n = only number for row
# -t = only text for row
# -a = any for row
nc=1; tc=1; nr=1; tr=1
if [ ${1:0:1} == "-" ]; then
    if [ ${1:1:1} == "n" ]; then
        tc=0
    elif [ ${1:1:1} == "t" ]; then
        nc=1
    fi
    if [ ${1:2:1} == "n" ]; then
        tr=0
    elif [ ${1:2:1} == "t" ]; then
        nr=1
    fi
    shift
fi
command="$1"
# Number or text value
column="$2"
row="$3"
ltrim="$4"
rtrim="$5"

columnNo=-1
rowNo=-1

exec < /dev/null

while read -r -a columns; do
    (( rowNo++ ))
    if (( columnNo == -1 )); then
        total="${#columns[@]}"
        columnNo=$(for (( i=0; i<$total; i++ ))
        {
            if [[ "${columns[$i]}" == "$column" && "$tc" == 1 ]] || [[ "$column" == "$i" && "$nc" == 1 ]]; then
                echo "$i"
                break
            elif (( i >= total - 1 )); then
                echo -1
                break
            fi
        })
    else
        if [[ "${columns[0]}" == "$row" && "$tr" == 1 ]] || [[ "$rowNo" -eq "$row" && "$nr" == 1 ]]; then
            str="${columns[columnNo]}"
            str=${str#"$ltrim"}
            str=${str%"$rtrim"}
            echo "$str"
            exit 0
        fi
    fi
done < <($command 2> /dev/null)
echo "Error! Could not be found."
exit 1

オプションのフラグと 3 ~ 5 個のパラメータ、コマンド、列 (数値またはテキスト値)、行 (数値またはテキスト値)、およびオプションで値を受け入れltrimますrtrim

これは、出力に複数のテーブルが含まれている場合、または出力にテーブルの一部ではない追加のテキストが含まれている場合に機能します。

./extract-table-entry.sh "cat table.txt" "Name" 1
# Output = (John)
./extract-table-entry.sh "cat table.txt" "Name" 5
# Output = (James)

括弧を削除するには、ltrimパラメータとrtrimパラメータを指定するだけです。

例えば:

./extract-table-entry.sh "cat table.txt" "Name" 5 "(" ")"
# Output = James

関連情報