Reputation: 91
I have a delimited string variable as mentioned below. I would like to grep a matched string. I found some possible solutions on the Internet, but sadly they did not give me the result I was expecting. Can you suggest or correct me.
Input: 123,src_12,234,456
1,23,34,src_23,4,56,7
src_14,12
12,3,5,src_5
Output: src_12
src_23
src_14
src_5
Logic: I need to fetch the string which has 'src_'. It's not always the second item in the list. The position may change. Variable length, delimited.
Upvotes: 0
Views: 366
Reputation: 8711
Using tr
$ cat srinath.txt2
123,src_12,234,456
1,23,34,src_23,4,56,7
src_14,12
12,3,5,src_5
src_6,src_7,16,18
$ A=$(cat srinath.txt2)
$ tr ',' '\n' <<< "$A" | grep ^src
src_12
src_23
src_14
src_5
src_6
src_7
Upvotes: 1
Reputation: 20002
Look for ^src_xxx,
, ,src_xxx,
and ,src_xxx$
, and only print the match without the ,
.
sed -rn 's/.*(,|^)(src_[^,]*)(,|$).*/\2/p'
Upvotes: 0
Reputation: 26481
A simple grep returning only (-o
) the matched words (-w
)
$ grep -wo 'src_[^,]*' file
src_12
src_23
src_14
src_5
Upvotes: 0
Reputation: 133488
With simple awk
solution:
awk 'match($0,/src_[0-9]+/){print substr($0,RSTART,RLENGTH)}' Input_file
or
awk '{sub(/.*src/,"src");sub(/\,.*/,"")} 1' Input_file
Upvotes: 1
Reputation: 58391
This might work for you (GNU sed):
sed '/\n/!s/src_[^,]*/\n&\n/g;/^src_/P;D' file
Surround all candidate strings by newlines and then using the sed commands P
and D
whittle down each line printing only the candidates with the prefix src_
.
Upvotes: 0
Reputation: 88583
With bash:
while IFS="," read -a array; do
for element in "${array[@]}"; do
[[ $element =~ ^src_ ]] && echo "$element"
done
done <<< "$variable"
Output:
src_12 src_23 src_14 src_5
Upvotes: 1
Reputation: 8711
Using Perl
$ cat srinath.txt
123,src_12,234,456
1,23,34,src_23,4,56,7
src_14,12
12,3,5,src_5
$ perl -nle ' /(src_\d+)/ and print $1 ' srinath.txt
src_12
src_23
src_14
src_5
If you have more than one src_ in the same line, then use below
$ cat srinath.txt2
123,src_12,234,456
1,23,34,src_23,4,56,7
src_14,12
12,3,5,src_5
src_6,src_7,16,18
$ perl -nle ' while( /(src_\d+)/g ) { print $1 } ' srinath.txt2
src_12
src_23
src_14
src_5
src_6
src_7
If it is in a variable, then
$ A=$(cat srinath.txt2)
$ perl -nle ' while( /(src_\d+)/g ) { print $1 } ' <<< "$A"
src_12
src_23
src_14
src_5
src_6
src_7
or
$ export A="123,src_12,234,456,1,23,34,src_23,4,56,7,src_14,12,12,3,5,src_5,src_6,src_7,16,18"
$ perl -nle ' while( /(src_\d+)/g ) { print $1 } ' <<< "$A"
src_12
src_23
src_14
src_5
src_6
src_7
$ perl -le ' $_=$ENV{A}; while( /(src_\d+)/g ) { print $1 } '
src_12
src_23
src_14
src_5
src_6
src_7
Upvotes: 0