我正在尝试 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/