How to find a pattern between the special characters { and \?

Viewed 83

I've been learning how to work with z/VM through the zLinux console. I've sent a CMS command to a z/VM guest and had the output return to a file on zLinux. Now all that is left is to cleanup the file and extract the right date through a pattern.

I noticed that the file contains the right data between a { and a \. The pattern opens with a { and ends with a . See the example below.

Example:

 &{HELLO WORLD TEST 123 \INMR06

There are many lines like these and I tried extracting the pattern using the commands:

  1. awk -F"[{\]" '{print $2}' TMPCMS

    Result: HELLO WORLD TEST 123 \INMR06

  2. awk -F"[{\\]" '{print $2}' TMPCMS

    Result: awk: warning: escape sequence \]' treated as plain ]'

               *HELLO WORLD TEST 123 \INMR06*
    

I would like to get only the string "HELLO WORLD TEST 123" between the { and \, and ignore "\INRM06".

I just don't seem to be able to escape that "\".

Yours truly,

Joeyb276


3 Answers

OP's code fix: Good try and you were close. If you do the escaping properly of \ character inside your field separator you could get it done. Written and tested with shown samples in GNU awk.

awk -F'{| \\\\' '{print $2}'  Input_file

Bonus solution: You could use match function of awk to match between { to \:

awk 'match($0,/{[^\\]*/){print substr($0,RSTART+1,RLENGTH-1)}' Input_file

You have to escape the escape of the back-slash. :D

awk -F'[{\\\\]' '{print $2}'

For this specific problem you can just use two sub(), it may be easier to read:

awk  'sub(/[^{]*{/,"")+sub(/\\.*/,"")'

You may use sed with the following command:

sed -n 's/^[^{]*{\(.*\)\\[^\\]*$/\1/p' TMPCMS

See an online sed demo.

The -n option suppresses default line output, the pattern matches

  • ^ - start of string
  • [^{]* - zero or more chars other than {
  • { - a { char
  • \(.*\) - Group 1: any zero or more chars
  • \\ - a \ char
  • [^\\]* - zero or more chars other than \
  • $ - end of string

The \1 replacement only keeps the value of Group 1 and p option prints it.

Related