Linux 如何使用 grep 修剪特定文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6284256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to trim specific text with grep
提问by James
I am in need of trimming some text with grep, I have tried various other methods and havn't had much luck, so for example:
我需要用 grep 修剪一些文本,我尝试了各种其他方法,但运气不佳,例如:
C:\Users\Admin\Documents\report2011.docx: My Report 2011
C:\Users\Admin\Documents\newposter.docx: Dinner Party Poster 08
How would it be possible to trim the text file, so to trim the ":" and all characters after it.
如何修剪文本文件,以便修剪“:”及其后的所有字符。
E.g. so the output would be like:
例如,输出将如下所示:
C:\Users\Admin\Documents\report2011.docx
C:\Users\Admin\Documents\newposter.docx
采纳答案by matchew
use awk?
使用awk?
awk -F: '{print ':'}' inputFile > outFile
you can use grep (note that -o returns only the matching text)
你可以使用 grep (注意 -o 只返回匹配的文本)
grep -oe "^C:[^:]" inputFile > outFile
回答by Chance
cat inputFile | cut -f1,2 -d":"
cat inputFile | cut -f1,2 -d":"
The -d
specifies your delimiter, in this case ":". The -f1,2
means you want the first and second fields.
在-d
指定的分隔符,在这种情况下“:”。这-f1,2
意味着您需要第一个和第二个字段。
The first part doesn't necessarily have to be cat inputFile
, it's just whatever it takes to get the text that you referred to. The key part being cut -f1,2 -d":"
第一部分不一定是cat inputFile
,它只是获取您引用的文本所需的任何内容。关键部分是cut -f1,2 -d":"
回答by brandizzi
That is pretty simple to do with grep -o
:
这很简单grep -o
:
$ grep -o '^C:[^:]*' input
C:\Users\Admin\Documents\report2011.docx
C:\Users\Admin\Documents\newposter.docx
If you can have other drives just replace C
by .
:
如果您可以使用其他驱动器,只需替换C
为.
:
$ grep -o '^.:[^:]*' input
If a line can start with something different than a drive name, you can consider both the occurrence a drive name in the beginning of the line and the case where there is no such drive name:
如果一行可以以不同于驱动器名称的名称开头,您可以考虑在行的开头出现驱动器名称和没有这样的驱动器名称的情况:
$ grep -o '^\(.:\|\)[^:]*' input
回答by Nicholas Sushkin
Your text looks like output of grep. If what you're asking is how to print filenames matching a pattern, use GNU grep option --files-with-matches
您的文本看起来像 grep 的输出。如果您要问的是如何打印匹配模式的文件名,请使用 GNU grep 选项 --files-with-matches