简体   繁体   中英

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. 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. As always, Awk solution is also appreciated.

You can use awk:

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

$1 is first field and $NF is last field in each record.

Through sed.

sed 's/[[:blank:]].*[[:blank:]]/ /' file

[[:blank:]].*[[:blank:]] would match all the characters from the first blank space upto the last blank space. Replacing all the matched chars with space will give you the desired output.

GREP

I add a solution using grep (Note: It is better to use awk or sed , it's just out of curiosity)

grep -E -o "^\S+\b" file | paste - <(grep -E -o "\b\S+$" file)

you get:

AA1AA   0,00
BE661N  0,02

BASH

Also, I added a solution using pure bash and parameter expansion

while read line; do 
  echo "${line/%\ */} ${line##* }";
done < file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM