【问题标题】:bash: a more effective way to search strings in a file and extract part of stringsbash:一种在文件中搜索字符串并提取部分字符串的更有效方法
【发布时间】:2014-04-04 17:02:59
【问题描述】:

我有一个输入文件如下:

some lines with quote and :
AGE:23
some lines with quote and :
NAME:2,0,"My Name Is"
some lines with quote and :

其实我是用这段代码从文件中提取信息的:

  age="$(cat "$file" | awk -F ':' '/AGE:/ { print $2 }')"
  name="$(cat "$file" | awk -F '"' '/NAME:/ { print $2 }' )"
  echo "age: $age"
  echo "name: $name"

输出:

age: 23
name: My Name Is

我正在寻找一种比两次运行 cat 和 awk 更好的方法。我有搜索在一条 cat/awk 行中进行,但无法弄清楚,在这种情况下不合适吗?谁能给我一个更好的方法吗?

提前致谢

【问题讨论】:

  • 您可以从不使用cat 开始。只需将文件名放在awk 命令的末尾:awk [OPTIONS] SCRIPT files...(例如:age="$(awk -F ':' '/AGE:/ { print $2 }' "$file")"
  • @rici 谢谢你指点我这个

标签: string bash file variables awk


【解决方案1】:
while IFS=: read key value; do
    case $key in
        AGE)  age=$value;;
        NAME) name=$(awk -F'"' '{print $2}' <<< "$value");;
    esac
done < "$file"

【讨论】:

    【解决方案2】:

    如果数据像您在问题中显示的那样简单。无需为此使用 shell,只需 awk 就足够了

    awk -F '"' '/AGE/{print tolower($0)}/NAME/{print "name:"$2}' input.txt
    

    【讨论】:

      【解决方案3】:

      我喜欢@JohnKugelman 的方法,但可以改进:使用冒号和引号作为字段分隔符:

      while IFS=':"' read -ra fields; do 
          case ${fields[0]} in 
              AGE)  age=${fields[1]}  ;; 
              NAME) [[ ${fields[1]} == "2,0," ]] && name=${fields[2]} ;; 
          esac
      done < file
      

      使用 awk,我会写:

      read age name < <(
          awk -F '[:,]' '
              $1 == "AGE" {printf "%s ",$2} 
              $1 == "NAME" && $2 == 2 && $3 == 0 {printf "%s ",$NF} 
              END {print ""}
          ' filename 
      )
      

      【讨论】:

      • 感谢您的回答,我正在使用while 解决方案,我忘了提及,不幸的是,我在源文件中(~250 行)表格中的其他行,例如@987654324 @ 代码返回错误的行。我怎么能匹配NAME:2,0, 我已经测试了NAME:2,0,) name=${fields[2]} ;;NAME[*2,0,]) 'NAME:2,0,') 没有运气
      • 以后,不要让我们猜你的要求。
      • 抱歉,考虑到我的第一个 awk 解决方案,我认为答案不会基于较短的匹配 AGE NAME,我从 bash 开始
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 2011-08-10
      • 2012-03-23
      • 2020-01-06
      相关资源
      最近更新 更多