【问题标题】:Using awk command in Bash在 Bash 中使用 awk 命令
【发布时间】:2017-11-25 04:14:25
【问题描述】:

我正在尝试使用 bash 脚本循环 awk 命令,但我很难在 awk 命令的单引号中包含一个变量。我想我应该完全在 awk 中做这件事,但我现在对 bash 感觉更舒服。

#!/bin/bash

index="1"

while [ $index -le 13 ]
do

    awk "'"/^$index/ {print}"'" text.txt

done

【问题讨论】:

  • 为什么不只是 grep "^$index" ?似乎为此目的使用 awk 太过分了......

标签: linux bash ubuntu awk gawk


【解决方案1】:
awk '/'"$index"'/' text.txt
# A lil play with the script part where you split the awk command
# and sandwich the bash variable in between using double quotes
# Note awk prints by default, so idiomatic awk omits the '{print}' too.

应该这样做,或者使用greplike

grep "$index" text.txt # Mind the double quotes

注意: -le 用于比较数字,因此您可以index="1" 更改为index=1

【讨论】:

  • '/'"$index"'/' 这是不好的做法,请改用-v varname="somevalue"
【解决方案2】:

使用标准方法——awk-v 选项来设置/传递变量:

awk -v idx="$index" '$0 ~ "^"idx' text.txt

在这里,我将变量idx 设置为具有shell 变量$index 的值。在awk 内部,我只是将idx 用作awk 变量。

$0 ~ "^"idx 匹配如果记录以 (^) 开头,无论变量 idx 包含什么;如果是,打印记录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 2015-03-21
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多