AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / computer / 问题 / 1649633
Accepted
Hot JAMS
Hot JAMS
Asked: 2021-05-18 04:34:41 +0800 CST2021-05-18 04:34:41 +0800 CST 2021-05-18 04:34:41 +0800 CST

在 awk 代码中使用 bash 变量

  • 772

以下用 bash 编写的函数包含对多列数据执行数学运算的 AWK 代码,并最终将结果保存在所有已处理 CSV 的输出文件中。

home="$PWD"
# folder with the outputs
rescore="${home}"/rescore 
# folder with the folders to analyse
storage="${home}"/results_bench
cd "${storage}"
# pattern of the csv file located inside each of sub-directory of "${storage}"
str='*str1.csv'

     rescore_data3 () {
str_name=$(basename "${str}" .csv)
mkdir -p "${rescore}"/"${str_name}"
# loop all directories contained target csv file
while read -r d; do
awk -F', *' -v OFS=', ' '
    FNR==1 {
        if (suffix)                             # suppress the empty line
            printf "%s %.3f (%d)\n", suffix, dGmin, dGminid
                                                # report the results for dGmin
        dGmin = ""                              # initialize the min value
        path=FILENAME
        sub(/\/[^/]+$/,"",path)
        prefix=suffix=FILENAME
        sub(/_.*/, "", prefix)
        sub(/\/[^\/]+$/, "", suffix); sub(/^.*_/, "", suffix)
        if (FNR==NR)
            print "lig(CNE)" " " "dG(" prefix ")" " " "ClusterID"        # print the header line
        next
    }
    {
        dG = sqrt((($3+10)/10)^2+(($2-100)/100)^2)
        if (dGmin == "" || dG < dGmin) {
            dGmin = dG                          # update the min dG value
            dGminid = $1                        # update the ID with the min dG
        }
    }
    END {
        printf "%s %.3f (%d)\n", suffix, dGmin, dGminid # report results for dGmin
    }
' "${d}_"*/${str} > "${rescore}/"${str_name}"/"${d%%_*}".csv"
done < <(find . -maxdepth 1 -type d -name '*_*_*' | awk -F '[_/]' '!seen[$2]++ {print $2}')
}

基本上每个处理的 CSV 包含 3 列:

#input_str1.csv located in the folder 10V1_cne_lig12
ID, POP, dG
1, 142, -5.6500 # the line with ID=1, has lowest value in dG
2, 10, -5.5000
3, 2, -4.9500
4, 150, -4.1200

对 5 个 CSV 文件应用 rescore_data3() 会产生以下输出(单行包含有关单个 csv 的信息):

# 10V1.csv
lig dG(10V1) ID
lig12 0.947 (1)
lig40 0.595 (1)
lig199 1.060 (1)
lig211 0.756 (2)
lig278 0.818 (1)

我需要修改 AWK 代码的数学方程中的常数(10 和 100),以便在为所有已处理的 csv 文件计算的灵活变量上使用它们替换:10 应替换为 dG 的最小值(每个输入的第 3 列.csv) 和 100 应替换为 POP 的最大值(每个 input.csv 的第 2 列)。最终,AWK 脚本中修改后的数学方程仍应包含 $2 和 $3 变量(针对特定 csv 获取的信息)以及 ${the_lowest_dG} 和 ${the_highest_POP}(在开始时仅对所有 CSV 计算一次):

dG = sqrt((($3-{the_lowest_dG})/{the_lowest_dG})^2+(($2-{the_highest_POP})/{the_highest_POP})^2)

已编辑: 这是一个可能的解决方案,它基于 glenn jackman 提出的 AWK 代码集成到我的函数中。为了计算所有输入 CSV 的最低 dG 和最高 POP ,我在我的 AWK 函数之前使用了这个 awk 代码(它也已经更新以接受这两个变量并在数学方程中进一步使用它):

rescore_data4 () {
# name of the target CSV file to be rescored
str_name=$(basename "${str}" .csv)
#make dir for output 
mkdir -p "${rescore}"/"${str_name}"
**# 1 - calculate max POP and dGmin for ALL rescored CSVs at once**
read highestPOP lowestDG < <(
    awk -F ', ' '
        FNR == 1 {next}
        NR == 2 || $2 > pop {pop = $2}
        NR == 2 || $3 < dg  {dg  = $3}
        END {print pop, dg}
    ' "${storage}"/*_*_*/${str} ## < applied on all *.csv files in each of the subdirectory matching *_*_* pattern
)
printf >&2 'DEBUG INFO: this is topPOP= %d and dGmin= %.1f computed for %s...  ' "${highestPOP}" "${lowestDG}" "${str_name}"; sleep 0.1 
#
# 2- Apply the following AWK code for rescoring and final data collecting
while read -r d; do
# run rescoring routine using the min/max values 
awk -F', *' -v OFS=', ' -v highest_POP="$highest_POP" -v lowest_dG="${lowestDG}" '
    FNR==1 {
        if (suffix)                             # suppress the empty line
            #print suffix " " dGmin " (" dGminid ")"
            printf "%s %.3f (%d)\n", suffix, dGmin, dGminid
            #printf "%s %.3f (%d) %.3f (%d)\n", suffix, dGmin, dGminid, dGmax, dGmaxid
                                                # report the results
        dGmin = ""                              # initialize the min value
        
        path=FILENAME
        sub(/\/[^/]+$/,"",path)
        prefix=suffix=FILENAME
        sub(/_.*/, "", prefix)
        sub(/\/[^\/]+$/, "", suffix); sub(/^.*_/, "", suffix)
        if (FNR==NR)
            print "lig(CNE)" " " "dG(" prefix ")" " " "ClusterID"        # print the header line
            #print "lig(CNE)" " " "dGmin(" prefix ")" " " "ID(dGmin)" " " "dGmax(" prefix ")" " " "ID(dGmax)"         # print the header line
        next
    }
    {
        dG = sqrt((($3-lowest_dG)/lowest_dG)^2+(($2-240)/240)^2)
        if (dGmin == "" || dG < dGmin) {
            dGmin = dG                          # update the min dG value
            dGminid = $1                        # update the ID with the min dG
        }
    }
    END {
        #print suffix " " dGmin " (" dGminid ")"    # report the results
        printf "%s %.3f (%d)\n", suffix, dGmin, dGminid
        #printf "%s %.3f (%d) %.3f (%d)\n", suffix, dGmin, dGminid, dGmax, dGmaxid
    }
' "${d}_"*/${str} > "${rescore}/"${str_name}"/"${d%%_*}".csv"
done < <(find . -maxdepth 1 -type d -name '*_*_*' | awk -F '[_/]' '!seen[$2]++ {print $2}')
}

虽然这通常效果很好,但新引入的 awk 部分存在一个错误:在包含超过 10 行的大量输入 CSV 的情况下,有时无法计算最低 DG 的值。

awk bash
  • 1 1 个回答
  • 76 Views

1 个回答

  • Voted
  1. Best Answer
    glenn jackman
    2021-05-18T04:48:40+08:002021-05-18T04:48:40+08:00

    在 awk 中,可以将$其视为用于获取给定字段编号的值的运算符。awk 变量和 C 变量一样,不需要用$.

    awk -F', *'\
        -v OFS=', ' \
        -v the_highest_POP="the_highest_POP" \
        -v the_lowest_dG="$the_lowest_dG" \
    '
        # ...
        dG = sqrt((($3 - the_lowest_dG) / the_lowest_dG)^2 + (($2 - the_highest_POP) / the_highest_POP)^2)
    

    我应该使用 bash 计算 ${the_highest_POP} 和 ${the_lowest_dG} (使用 while 一次处理所有 CSV),将它们存储在外部变量中并将它们提供给 awk,[...] 或者是否可以执行所有步骤直接在 AWK 代码中

    这完全取决于some_method_to_cumpute_highest_POP_for_all_csvs_in_d


    啊,我明白了。我没有仔细阅读这个问题。您将不得不处理文件两次,一次是找到最小/最大值,另一次是进行 dG 计算。为了可读性,我会使用 2 个单独的 find/awk 调用来做到这一点:

    # get the files you want to operate on.
    # I'm assuming there are not hundreds of them.
    mapfile -t cvsFiles < <(
        find . -maxdepth 1 -type d -name '*_*_*' |
        awk -F '[_/]' '!seen[$2]++ {print $2}')
    )
    
    # get the min/max values
    read highestPOP lowestDG < <(
        awk -F ', ' '
            FNR == 1 {next}
            NR == 2 || $2 > pop {pop = $2}
            NR == 2 || $3 < dg  {dg  = $3}
            END {print pop, dg}
        ' "${csvFiles[@]}"
    )
    
    # do the calculations over all the files
    awk -F', *'\
        -v OFS=', ' \
        -v the_highest_POP="$highestPOP" \
        -v the_lowest_dG="$lowestDG" \
    '...' "${files[@]}"
    
    • 1

相关问题

  • 在 macOS High Sierra 的终端中设置环境变量时遇到问题

  • 对于 cp 或 mv,是否有等同于 cd - 的东西?

  • Notify-发送窗口下出现的通知

  • 如何从 WSL 打开 office 文件

  • awk 根据变量匹配提取文件中的特定模式

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    如何减少“vmmem”进程的消耗?

    • 11 个回答
  • Marko Smith

    从 Microsoft Stream 下载视频

    • 4 个回答
  • Marko Smith

    Google Chrome DevTools 无法解析 SourceMap:chrome-extension

    • 6 个回答
  • Marko Smith

    Windows 照片查看器因为内存不足而无法运行?

    • 5 个回答
  • Marko Smith

    支持结束后如何激活 WindowsXP?

    • 6 个回答
  • Marko Smith

    远程桌面间歇性冻结

    • 7 个回答
  • Marko Smith

    子网掩码 /32 是什么意思?

    • 6 个回答
  • Marko Smith

    鼠标指针在 Windows 中按下的箭头键上移动?

    • 1 个回答
  • Marko Smith

    VirtualBox 无法以 VERR_NEM_VM_CREATE_FAILED 启动

    • 8 个回答
  • Marko Smith

    应用程序不会出现在 MacBook 的摄像头和麦克风隐私设置中

    • 5 个回答
  • Martin Hope
    Saaru Lindestøkke 为什么使用 Python 的 tar 库时 tar.xz 文件比 macOS tar 小 15 倍? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh 如何减少“vmmem”进程的消耗? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Windows 10 搜索未加载,显示空白窗口 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    v15 为什么通过电缆(同轴电缆)的千兆位/秒 Internet 连接不能像光纤一样提供对称速度? 2020-01-25 08:53:31 +0800 CST
  • Martin Hope
    andre_ss6 远程桌面间歇性冻结 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney 为什么在 URL 后面加一个点会删除登录信息? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension 鼠标指针在 Windows 中按下的箭头键上移动? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca 我所有的 Firefox 附加组件突然被禁用了,我该如何重新启用它们? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK 是否可以使用文本创建二维码? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 更改 git init 默认分支名称 2019-04-01 06:16:56 +0800 CST

热门标签

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve