简体   繁体   English

Grep并仅打印字符串的开头和结尾

[英]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解决方案也很受欢迎。

You can use awk: 你可以使用awk:

awk '{print $1, $NF}' file
AA1AA 0,00
BE661N 0,02

$1 is first field and $NF is last field in each record. $1是第一个字段, $NF是每个记录中的最后一个字段。

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添加一个解决方案(注意:最好使用awksed ,这只是出于好奇)

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.

相关问题 使用grep的正则表达式匹配字符串的开头和结尾 - Regular expression using grep to match the beginning and end of a string 正则表达式匹配字符串中的begin([)和end(,)(仅) - Regex to match beginning([) and and end(,) (only) in a string sed和grep中单词的开头和结尾 - Beginning and end of words in sed and grep 正则表达式 - 或 _ 在字符串的开头或结尾 - Regex for - or _ at beginning or end of string 仅在两者都存在时才从开头和结尾处删除引号 - remove quotation marks from string at beginning and end only if both are present 正则表达式不匹配字符串末尾的整个单词(bigram),仅在开头和中间 - Regex not matching a whole word (bigram) at the end of a string, only at the beginning and middle 正则表达式仅接受字母和空格,并且在字符串的开头和结尾不允许使用空格 - Regex to accept only alphabets and spaces and disallowing spaces at the beginning and the end of the string 如何使用Regex仅获取字符串开头和结尾的数字? - How to get only numbers at the beginning and end of a character in string with Regex? 正则表达式 - 在字符串的开头和结尾允许 * 并且只允许 * - Regex- Allow * in the beginning and in the end of a string and allow only * RegEx在字符串内只有一个点不在开头或结尾 - RegEx only one dot inside string not at beginning or end
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM