SwimJim
SwimJim

Reputation: 109

sed only print substring in a string

I am trying to get a substring in a string that is in a large line of data. The regex (INC............) matches the substring I am trying to get the value of at https://regexr.com/, but I am unable to get the value of the substring into a variable or print it out.

The part of the string around this value is

......TemplateID2":null,"Incident Number":"INC000006743193","Priority":"High","mc_ueid":null,"Assint......

I am getting the error char 26: unknown option to `s' when I try this or the entire string is printed out.

cat /tmp/file1 | sed -n  's/\(INC............\)/\1/p'

cat /tmp/file1 | sed -n 's/./*\(INC............).*/\1/'

Upvotes: 0

Views: 216

Answers (2)

vintnes
vintnes

Reputation: 2030

That looks like JSON. If it's got {braces} around it which you cut out before posting (tsk tsk), you should definitely use jq if it's available. That said, this page needs some awk!

POSIX (works everywhere):

awk 'match($0, /INC[^"]+/) {print substr($0, RSTART, RLENGTH)}' /tmp/file1`

GNU (works on GNU/Linux):

gawk 'match($0, /INC[^"]+/, a) {print a[0]}' /tmp/file1

If you have more than one match per line (GNU):

gawk '{while(match($0=substr($0, RSTART+RLENGTH), /INC[0-9]+/, a)) print a[0]}' /tmp/file1

Upvotes: 0

choroba
choroba

Reputation: 242443

Using sed, you need to remove what precedes and follows the string:

 sed 's/.*\(INC............\).*/\1/' file

But you can also use grep, if your implementation supports the -o option:

grep -o 'INC............' file

Perl can be used, too:

perl -lne 'print $1 if /(INC............)/' file

Upvotes: 2

Related Questions