I have a script that create a txt file with a lot of information. I want to check if there is a specific text in it, and copy what come after. for example, this is the txt file:


where I want to check if WANTEDTEXT is exist and if so, copy what come next in [ and ] aka TEXTTOCOPY.


  • well, I did "grep "WANTEDTEXT" input.txt > output.txt" but it also give me the text that I already know. I need just what come after, and I don't know how to do that... @GypsyCosmonaut – M margaliot Aug 10 '17 at 18:57
  • I mean, it did copy what come after but it also copy the text that I search for, and that I don't want... – M margaliot Aug 10 '17 at 19:01
> echo blablablaWANTEDTEXT[TEXTTOCOPY]blablabla... | 
> awk -v searchtext=WANTEDTEXT '$0 ~ searchtext "\\[.*\\]" {
    strstart=index($0,searchtext "[")+length(searchtext)+1;
    tmpstr=substr($0,strstart); sub("].*$","",tmpstr); print tmpstr; } '

  • 1
    Complicated, clumsy and without explanation, so the OP won't learn to help himself. – Philippos Aug 11 '17 at 6:05
echo '....' | grep -oP 'WANTEDTEXT\[\K[^]]*'

Where you operate grep in the Perl mode, meaning, you can write Perl regexes in grep and the -o will print just the matching portion, instead of the whole line as is it's wont.

Note: Any thing to the left of \K will not show up in the output. It's a sort of a keeper flag (lookbehind but variable length) that instructs grep to use it in matching but NOT outputting.


greptext=$(echo blablablaWANTEDTEXT[TEXTTOCOPY]blablabla | grep "WANTEDTEXT")
if [[ -n $greptext ]]; then
  ftext=$(echo "blablablaWANTEDTEXT[TEXTTOCOPY]blablabla" | cut -d'[' -f2 | cut -d']' -f1)
  echo $ftext

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.