2013-05-05 45 views
0

我使用这个istruction打印grep的输出:的Unix - 为了

VAR=$(grep -r -i --color=always --exclude=\*.{sh,pdf,doc,docx} "$WORD" "$DIRECTORY") 

这给了我这样的输出:

/dir1NameWithSpaces/File1_05012004/file6.sml:file6 content .... with words and symbols 
/dir1NameWithSpaces/File1_05012004/fil3.txt:file3 content .... with words and symbols 
/dir1NameWithSpaces/File1_04092008/file.txt:file content .... with words and symbols 

我需要提取每行(例如使用循环)并在1行上仅打印来自grep的文件名,并在其他行上打印grep命令的内容。

它必须是通用的,以便每次在多文件内容中搜索时使用它。

此外,如果您正在考虑直接使用grep,那么包含内容的行不必具有文件名,所以我只想留下“:”符号。

为了清楚这里是一个例子:

/dir1NameWithSpaces/File1_05012004/file6.sml: 
:file6 content .... with words and symbols 
/dir1NameWithSpaces/File1_05012004/fil3.txt: 
file3 content .... with words and symbols 
/dir1NameWithSpaces/File1_04092008/file.txt: 
file content .... with words and symbols 

换句话说我的grep的输出必须被tadily打印。

感谢

+1

是否有关闭')'的'$失踪()'构建? – Jens 2013-05-05 16:52:01

+1

当你想要格式化输出时,切换到'awk'。与'awk'结合的'find'很容易控制和定制 – abasu 2013-05-05 17:10:53

+0

是的,谢谢你,你是对的 – Frank 2013-05-05 17:40:49

回答

3
$ echo foo | tee bar.txt baz.txt qux.txt 
foo 

$ grep -r foo . | sed 'y/:/\n/' 
./bar.txt 
foo 
./baz.txt 
foo 
./qux.txt 
foo