[英]Grep and print only beginning and end of a string
I have a list of strings, they are product codes followed by product description and the price. 我有一个字符串列表,它们是产品代码,后跟产品描述和价格。 I would like to
Grep
and print only the product codes and the prices. 我想
Grep
并只打印产品代码和价格。 Product codes are combinations of capital letters and digits and the prices are digits and a comma as a decimal mark. 产品代码是大写字母和数字的组合,价格是数字,逗号是小数点。 Codes, descriptions and prices are separated with a space, like:
代码,描述和价格用空格分隔,如:
AA1AA This is an example for free 0,00
BE661N For your 0,02
and the output would be: 输出将是:
AA1AA 0,00
BE661N 0,02
I have tried several regexps in combination with -o
and -v
switches but failed miserably. 我已经尝试了几个与
-o
和-v
开关组合的regexp但是失败了。 As always, Awk
solution is also appreciated. 一如既往,
Awk
解决方案也很受欢迎。
Through sed. 通过sed。
sed 's/[[:blank:]].*[[:blank:]]/ /' file
[[:blank:]].*[[:blank:]]
would match all the characters from the first blank space upto the last blank space. [[:blank:]].*[[:blank:]]
将匹配从第一个空格到最后一个空格的所有字符。 Replacing all the matched chars with space will give you the desired output. 用空格替换所有匹配的字符将为您提供所需的输出。
GREP GREP
I add a solution using grep
(Note: It is better to use awk
or sed
, it's just out of curiosity) 我使用
grep
添加一个解决方案(注意:最好使用awk
或sed
,这只是出于好奇)
grep -E -o "^\S+\b" file | paste - <(grep -E -o "\b\S+$" file)
you get: 你得到:
AA1AA 0,00 BE661N 0,02
BASH BASH
Also, I added a solution using pure bash
and parameter expansion 此外,我添加了一个使用纯
bash
和参数扩展的解决方案
while read line; do
echo "${line/%\ */} ${line##* }";
done < file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.