如何从表中提取特定数据?

如何从表中提取特定数据?

这是表格...

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 组。我应该使用哪些 bash 命令或脚本(组合)来显示以下输出

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

相关内容