将匹配的字符串显示到行尾
Display matched string to end of line
如何在文件中查找特定字符串并显示匹配的字符串和该行的其余部分?
例如-我在a.txt
中有一行:
This code gives ORA-12345 in my code.
所以,我正在查找字符串 'ORA-'
输出应该是:
ORA-12345 in my code
尝试使用 grep:
grep 'ORA-*' a.txt
但它在输出中给出了整行。
# Create test data:
echo "junk ORA-12345 more stuff" > a.tst
echo "junk ORB-12345 another stuff" >> a.tst
# Actually command:
# the -o (--only-matching) flag will print only the matched result, and not the full line
cat a.tst | grep -o 'ORA-.*$' # ORA-12345 more stuff
正如 fedorqui 指出的那样,您可以使用:
grep -o 'ORA-.*$' a.tst
awk 中的附加答案:
awk '[=10=] ~ "ORA" {print substr([=10=], match([=10=], "ORA"))}' a.tst
从内到外,这是正在发生的事情:
match([=11=], "ORA")
查找行中出现 ORA
的位置。在这种情况下,它恰好是位置17.
substr([=13=], match([=13=], "ORA"))
然后 returns 从位置 17 到行尾。
[=14=] ~ "ORA"
确保以上仅适用于包含 ORA
.
的那些行
和sed
echo "This code gives ORA-12345 in my code." | sed 's/.*ORA-/ORA-/'
如何在文件中查找特定字符串并显示匹配的字符串和该行的其余部分?
例如-我在a.txt
中有一行:
This code gives ORA-12345 in my code.
所以,我正在查找字符串 'ORA-'
输出应该是:
ORA-12345 in my code
尝试使用 grep:
grep 'ORA-*' a.txt
但它在输出中给出了整行。
# Create test data:
echo "junk ORA-12345 more stuff" > a.tst
echo "junk ORB-12345 another stuff" >> a.tst
# Actually command:
# the -o (--only-matching) flag will print only the matched result, and not the full line
cat a.tst | grep -o 'ORA-.*$' # ORA-12345 more stuff
正如 fedorqui 指出的那样,您可以使用:
grep -o 'ORA-.*$' a.tst
awk 中的附加答案:
awk '[=10=] ~ "ORA" {print substr([=10=], match([=10=], "ORA"))}' a.tst
从内到外,这是正在发生的事情:
match([=11=], "ORA")
查找行中出现 ORA
的位置。在这种情况下,它恰好是位置17.
substr([=13=], match([=13=], "ORA"))
然后 returns 从位置 17 到行尾。
[=14=] ~ "ORA"
确保以上仅适用于包含 ORA
.
和sed
echo "This code gives ORA-12345 in my code." | sed 's/.*ORA-/ORA-/'