linux - grep 双引号内的字符串

标签 linux sed grep

我正在尝试 grep 路径字符串,所有内容都在双引号内。 For 循环遍历 test.txt 文件,它在 new1.xml 中搜索匹配项。如果找到,它会在路径内打印出一个字符串。

预期输出

abc/test/test
abc/test/test
cd/test1/test2
cdf

测试.txt

test/test
test/test
test1/test2
test1

new1.xml

<abc name="test/test" path="abc/test/test"  />
<abc name="test/test1" path="abc/test/test1"  />
<abc name="test1/test2" path="cd/test1/test2" />
<path="cdf" name="test1" />

脚本

for f in test.txt
    do
    echo "Processing $f"
        paste $f | while read lines; do
            results=`cat new1.xml | grep -o "name.*$lines.*" | grep -o 'path.*' | sed 's/[^"]*"\([^"]*\)".*/\1/'`
        done
    done

输出

abc/test/test
abc/test/test1

最佳答案

您可以更有效地编写循环并使用 sed 而不是多个 grep 来获得您想要的内容:

for f in test.txt; do
  echo "Processing $f"
  while read line; do
    grep 'name="'$line'"' new1.xml 
  done < "$f" | sed -E 's/.+path="([^"]+)".+/\1/'
done

对于您的示例,上面的脚本给出了以下输出:

Processing test.txt
abc/test/test

如果你只是处理一个文件,你不需要外循环:

  while read line; do
    grep 'name="'$line'"' new1.xml
  done < "test.txt" | sed -E 's/.+path="([^"]+)".+/\1/'

关于linux - grep 双引号内的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42285269/

相关文章:

c - scanf 没有被调用

linux - 无法为我崩溃的程序创建核心文件

bash - 如何创建 Linux 脚本(bash、sed、awk...)以在配置文件的特定部分添加一行

macos - 将命令的输出解析为变量 LIVE(网络流量监控)

list - 将参数传递给 Maxima CAS 中的函数

git - 如何在git repo中grep文件?

linux - 在构建面向性能的 linux 服务器以运行不同的应用程序时如何选择硬件?

c++ - 在 linux 上使用 c++ 中的键退出无限循环

linux - 如何使用grep从txt文件中获取大于50的数字

regex - awk 跳过空行