10

I have a large text file where a part of it looks like this (edited values):

JULIANA XXXX006060 LI1033322 THC BRL 730.00
XXXX006296 AA1004737 THC BRL 1,740.00
SANTOS JULIANA XXXX006668 AA1004786 THC BRL 8,150.00
SANTOS JULIANA CABINDA XXXX006697 AA1004777 THC BRL 2,325.00
SANTOS JULIANA XXXX006699 AA1004790 THC BRL 2,325.00
JULIANA BATA XXXX006141 CCC012946 THC BRL 1,460.00
JULIANA BATA XXXX006153 CCC013054 THC BRL 870.00
JULIANA XXXX006269 CCC013105 THC BRL 870.00
JULIANA XXXX006295 CCC013083 THC BRL 870.00
JULIANA BATA XXXX006305 CCC013043 THC BRL 1,460.00

I want to always grab (with a cut or awk or something else) the string that starts with XXXX00, but it's never in the same field number.

How can I do that in a shell-script?

5 Answers 5

13

Just grep for it:

grep -oE 'XXXX00[0-9]*' file
  • -o: Prints only the matching part.
  • -E: Activates extended regular expressions.
  • [0-9]*: After the string to search, only numbers should appear.
1
  • Note that the regex does not need the -E option (though it does no harm). Nov 28, 2015 at 18:08
6

It appears you want the 5th field from the right, so

awk '{print $(NF-4)}' file
0
3

Using grep with PCRE:

% grep -Po '(^|\s)\KXXXX00[^\s]*(?=(\s|$))' file.txt
XXXX006060
XXXX006296
XXXX006668
XXXX006697
XXXX006699
XXXX006141
XXXX006153
XXXX006269
XXXX006295
XXXX006305

You can get away with -w (word) in this case, note that the word constituent characters are considered as [[:alnum:]_]:

% grep -wo 'XXXX00[^ ]*' file.txt
XXXX006060
XXXX006296
XXXX006668
XXXX006697
XXXX006699
XXXX006141
XXXX006153
XXXX006269
XXXX006295
XXXX006305
0
2

A couple of other ways

With GNU awk

awk -vRS='[[:space:]]+' '/^X{4}0{2}/' file

With older versions of GNU awk, --re-interval could be needed, so

awk --re-interval -vRS='[[:space:]]+' '/^X{4}0{2}/' file

With tr and grep

<file tr -s '[:space:]' '[\n*]' | grep '^X\{4\}0\{2\}'
1
sed 's/[^0]*  *\([^ ]*\).*/\1/' <in >out

it looks like the field counts are different because you've got a list of people there, and they have different numbers of names. but probably none of them have a name with 0 in it, so just cut away completely up to the first space delimited string with one in it, save it, and cut all that follows.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .