Shanker
Shanker

Reputation: 15

regex usage to find a pattern

I have a task to do in my bash script. That I must read through a file and store all each word Custom in to array. means my array will contain. {"Custom_KEHJEO" "Custom_TTT_LEJEB_Adaptor" "ustom_SDE_Universal_Adaptor_EEEEEE"}

I can read through the content of file starting from line 9 using sed command but unable to pick up 'Custom*' strings and store into array.

there is a file lets say ~ folders.txt with below content, starting from line 9 which is always the case, I have following text.... ...and ending the last 3 lines also exactly same as below except date changes.

Custom_KEHJEO
Custom_TTT_LEJEB_Adaptor
Custom_SDE_Universal_Adaptor_EEEEEE
Custom_SIL_XXXXXXX
Custom_SIL_UUUUUUU
SDE_PSFT_89_Adaptor
SDE_SBL_78_Adaptor
UA_SDE
SILOS
SDE_SBL_Vert_811_Adaptor
SDE_JDEE1_90_Adaptor
SDE_Universal_Adaptor
Custom_SIL_XJGADWG
Custom_SIL_UUUUUUAAFE
SDE_ORAR12_Adaptor
SDE_JDEE1_811SP1_Adaptor
SDE_ORAR1212_Adaptor
SDE_ORA11510_Adaptor
SDE_SBL_80_Adaptor
Custom_SIL_MKEIHE
Custom_SDE_GAHWYWB
.listobjects completed successfully.

Completed at Thu Jan 22 12:46:39 2015

Upvotes: 0

Views: 40

Answers (2)

rchang
rchang

Reputation: 5246

This will go ahead and pass each string as a parameter to your other executable.

INPUTFILE=folders.txt
for string in `tail -n+9 $INPUTFILE | grep ^Custom`; do
  othercommand $string
done

I just saw @Wintermute's answer, which is a good one. If you actually need to capture these strings in an array for additional purposes other than just to pass to another command, @Wintermute's is more appropriate.

Upvotes: 0

Wintermute
Wintermute

Reputation: 44073

The sanest way to do this is probably grep:

arr=($(grep ^Custom filename))

# arr is now a bash array containing all tokens that begin with Custom
echo "${arr[@]}"

You could also do it with sed:

arr=($(sed '/^Custom/!d' filename))

...but grep is really made for this. Note that this hinges on a file structure with one token per line.

Upvotes: 1

Related Questions