如何從表中提取特定資料?

如何從表中提取特定資料?

這是表...

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

我想提取屬於同一組的人名。這裡 John 和 James 屬於第 2 組。

John
James

我使用了不同類型的 grep 組合。但似乎不起作用。

答案1

你可以sed這樣使用:

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

或者awk像這樣:

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

第一個解決方案在列印之前用括號內的字串替換該行。第二種解決方案使用括號作為字段分隔符,然後僅列印字段二(包含的字串)。

答案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 個參數、命令、列(數字或文字值)和行(數字或文字值)以及可選的ltrimrtrim值。

當輸出包含多個表或輸出包含不屬於表的額外文字時,它會起作用。

./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

相關內容