【问题标题】:unable to extract data inside square brackets in bash无法在bash中提取方括号内的数据
【发布时间】:2016-03-24 07:24:07
【问题描述】:

我有类似的输入(输出.txt 有将近 2000 行)

定理 定理 [“A B C D”] 定理 定理 ["e","f","g","h"]

我的 output1.txt 应该是

一种 b C d e F G H

首先,我试图将 [] 中的所有值放在一个文件中。但最终我的目标是实现 output1.txt。如果有人帮助我一次性完成(提取 [] 内的数据并删除“”和逗号并在每一行中放置值),那就太好了。

我的代码截至目前

    reg="\[([^]]+)\]"
    while IFS='' read -r line || [[ -n "$line" ]]; do
    if [[ $line = ~$reg ]] ; then echo "$line" >>      home/hdpsrvc/sandeep/hbase/output1.txt ; fi
    done < /home/hdpsrvc/sandeep/hbase/output.txt

文件未在指定路径中创建,并且在终端上也没有错误。我按照以下stackoverflow链接编写上述代码

shell script. how to extract string using regular expressions Regular expression to extract text between square brackets

【问题讨论】:

  • 您使用了= ~$reg 而不是=~ $reg。如果您首先测试您链接到的代码以确保其正常工作,然后逐渐适应它并准确查看您卡在哪一点上,您自己就会变得更轻松
  • 太棒了..谢谢。你是对的。你能告诉我我应该如何像 output1.txt 一样提取
  • reg="\[([^]]+)\]" reg1="(["'])(?:(?=(\\?))\2.)*?\1" while IFS='' read -r line || [[ -n "$line" ]]; do if [[ $line =~ $reg ]] then if [[ $line =~ $reg1 ]] then echo "1" echo "$line" &gt;&gt; /home/hdpsrvc/sandeep/hbase/output1.txt fi fi done &lt; /home/hdpsrvc/sandeep/hbase/output.txt 我收到错误消息 extract1.sh: line 3: unexpected EOF while looking for matching `'' extract1.sh: line 13: syntax error: unexpected end of file I follow this link [stackoverflow.com/questions/171480/…

标签: regex bash shell unix logic


【解决方案1】:

awk 可以轻松做到这一点:

cd /home/hdpsrvc/sandeep/hbase

awk -F'[][," ]+' '/\[.*\]/{for (i=2; i<NF; i++) print $i}' output.txt > output1.txt
a
b
c
d
e
f
g
h

【讨论】:

  • 不,它从 output.txt 中获取输入(行变量从 output.txt 中读取每一行)。那么现在你能告诉我将 output.txt 放在哪里吗?
  • 我知道 output1.txt 是我的输出。但我的输入文件是 output.txt。如果您看到我的代码,则有 2 个不同的文件。我在问 output.txt。感谢您的时间和精力
  • 很抱歉给您带来了困扰。我在问题中的代码在 extract.sh 中。那么我可以删除我的整个代码并放置您的 awk 代码吗?
  • 是的,当然,删除所有代码并使用这个 awk。 Also check this demo
  • 哇。极好的。感谢您的时间和精力。也非常感谢您根据我的要求修改您的答案。我接受你的回答。再次感谢
猜你喜欢
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
相关资源
最近更新 更多