You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将awk循环变量i的值赋值给Bash变量?

Capture Awk Column Number into a Bash Variable

Hey there! I see you've got a working script that finds the column number of a matching field in your temp file, and now you want to store that column number in a Bash variable to use elsewhere. Let's fix that up easily.

The Problem with Your Current Script

Your existing awk command prints the column number correctly, but the output just goes to stdout—we need to capture that output into a Bash variable instead. Also, embedding the Bash variable $sword6 directly into the awk script with single quotes can lead to quoting issues (like if your search term has spaces or special characters), so we'll fix that too.

Modified Script with Variable Capture

Here's the updated script that captures the matching column number(s) into a Bash variable:

#!/bin/bash
set -x
read -p "Enter :" sword6

# Pass the search term to awk safely with -v, then capture output into column_numbers
column_numbers=$(awk -v search_term="$sword6" '
    BEGIN{IGNORECASE = 1 } 
    { 
        for(i=1;i<=NF;i++) { 
            if ($i ~ search_term"$") { 
                print i; 
            } 
        } 
    }' /root/scripts/pscripts/tempprint.txt)

# Now you can use the $column_numbers variable anywhere in your script
echo "Matched column number(s): $column_numbers"

Key Changes Explained

  1. Safe Variable Passing: Using awk -v search_term="$sword6" passes your input search term directly to awk as an awk variable, avoiding messy quote escaping. This is way more robust if your search terms ever include spaces or special characters.
  2. Command Substitution: The $(...) syntax captures all output from the awk command and stores it in the column_numbers Bash variable.

Handling Multiple Matches

If your search term matches multiple columns (e.g., searching for "m" might match columns 2, 3, and 8 in your sample data), you can store the results in an array to access individual values:

# Convert the space-separated column numbers into an array
read -ra column_array <<< "$column_numbers"

# Access the first matched column
echo "First match: ${column_array[0]}"

# Loop through all matched columns
echo "All matches:"
for col in "${column_array[@]}"; do
    echo "- Column $col"
done

Example Usage

If you run the script and enter sam, the column_numbers variable will hold 2, and you can use that value for whatever logic you need next in your script.

内容的提问来源于stack exchange,提问作者Nike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:09:10