使用awk动态表宽度

问题描述 投票:0回答:1

是否有更复杂的方法使用 awk 来格式化表格?我当前的代码并没有完全按照我的预期进行,如果通过管道传输到

| column -t
,PATTERN 列将显示所有单词。

main() {
    read -p "Enter a full path for search: " path
    read -p "Enter a pattern to search for: " pattern
    printf "\n"

    # Use process substitution to capture the grep output
    output=$(grep -inR "$pattern" "$path")

    if [ -n "$output" ]; then
        # Use awk to format the output into a table-like view
        echo "$output" | awk -F: 'BEGIN { printf "%-100s %-5s %-20s\n", "FILE", "LINE", "PATTERN"
                                      printf "%-100s %-5s %-20s\n", "----", "----", "-------" }
                                    { printf "%-100s %-5s %-20s\n", $1, $2, $3}' | column -t
    else
        echo "No matching results found."
    fi
}

输出:

FILE                                                                                    LINE  PATTERN                        
----                                                                                    ----  -------                        
/home/user/shell-scripting-ex/Shell-scripting/scripts/new/grep_usage.sh               32    #        Main  function        
/home/user/shell-scripting-ex/Shell-scripting/scripts/new/grep_usage.sh               72    #        Call  the       main  function
/home/user/shell-scripting-ex/Shell-scripting/scripts/new/random_number_generator.sh  32    #        Main  function        
/home/user/shell-scripting-ex/Shell-scripting/scripts/new/random_number_generator.sh  37    #        Call  the       main  function
bash awk scripting grep format
1个回答
0
投票
$ { echo -e "FILE:LINE:PATTERN\n---:----:----"; cat file; } | 
   column -ts:


FILE                                                                                  LINE  PATTERN
---                                                                                   ----  ----
/home/user/shell-scripting-ex/Shell-scripting/scripts/new/grep_usage.sh               32    # Main function        
/home/user/shell-scripting-ex/Shell-scripting/scripts/new/grep_usage.sh               72    # Call the main function
/home/user/shell-scripting-ex/Shell-scripting/scripts/new/random_number_generator.sh  32    # Main function        
/home/user/shell-scripting-ex/Shell-scripting/scripts/new/random_number_generator.sh  37    # Call the main function

如果你想让下划线与标题字长匹配,你需要一些额外的代码。

© www.soinside.com 2019 - 2024. All rights reserved.