bash 如何修改GREP输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9233971/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:32:02  来源:igfitidea点击:

How to modify GREP output?

linuxbashshellgrep

提问by knittl

I have a script which uses grep to output like this:

我有一个脚本,它使用 grep 输出如下:

12 Apples
10 Grapes
11 Mangoes

I want to the output as

我想输出为

Apples: 12 Grapes: 10 Mangoes: 11

How to modify the grep output?

如何修改grep输出?

回答by FatalError

You could pipe to awk like:

您可以通过管道传输到 awk,例如:

$ echo "
12 Apples
10 Grapes
11 Mangoes
" | awk 'BEGIN { OFS=": "; ORS=" "; } NF >= 2 { print , ; }'
Apples: 12 Grapes: 10 Mangoes: 11 

replacing, of course, the echo cmd with the grepyou are doing.

当然,将 echo cmd 替换为grep您正在执行的操作。

回答by Dan Fego

I'd use awk:

我会用awk

$ grep regex file | awk '{ printf "%s: %d ", ,  }; END { printf "\n" }'
Apples: 12 Grapes: 10 Mangoes: 11 

This would use printfto print out your lines to the specified format, and then add a newline at the end, since that's what you probably want. If you're not familiar with awk, $1and $2represent positional parameters, which is to say, the first (in this case, space-separated) field, and the second.

这将用于printf将您的行打印为指定的格式,然后在末尾添加一个换行符,因为这可能是您想要的。如果您不熟悉awk,$1$2表示位置参数,也就是说,第一个(在本例中为空格分隔)字段和第二个字段。

回答by knittl

You can use sed:

您可以使用 sed:

grep … | sed 's/^\([0-9]*\) \(.*\)$/: /'

回答by William Pursell

If you are willing to have no spaces around the colon in the output you can simply do:

如果您愿意在输出中的冒号周围没有空格,您可以简单地执行以下操作:

$ grep ... | tr ' 2' ': '; echo 

This just changes the spaces to colons and the newlines to spaces. The echo is there to give a trailing newline.

这只是将空格更改为冒号,将换行符更改为空格。回声在那里给出一个尾随换行符。

回答by ДМИТРИЙ МАЛИКОВ

Using ghc:

使用ghc

$> cat ./text 
12 Apples
10 Grapes
11 Mangoes

$> cat ./text  | ghc -e "getContents >>= putStrLn . concatMap ((\(num,name) -> (drop 1 name) ++ \": \" ++ num ++ \" \") . break (== ' ')) . lines"
Apples: 12 Grapes: 10 Mangoes: 11

回答by potong

This might work for you:

这可能对你有用:

echo -e "12 Apples\n10 Grapes\n11 Mangoes" |
sed ':a;$!{N;ba};s/\(\S*\) \(\S*\)\n*/:  /g'
Apples: 12 Grapes: 10 Mangoes: 11