1
echo "abcdef12cade 12345678 abcdefba12345678" | sed -E "s/[0-9a-fA-F]{8}/00000000/g" 

the above outputs the following

00000000cade 00000000 0000000000000000

it is replacing the pattern for second occurrence in a same word. I don't want to replace if there is a second occurrence.

expected ouput

00000000cade 00000000 abcdefba12345678
0

3 Answers 3

4

If you only want to replace the first occurrence of a match, don't use the g suffix to the command:

$ echo 'aa' | sed 's/a/b/g'
bb
$ echo 'aa' | sed 's/a/b/'
ba

The g option stands for 'global', which is explicitly telling sed to replace all matches and not just the first (which is the default behavior).

0
2

It seems like you're looking for words that are between 8 and 15 chars, and replace the first 8 hex digits:

sed -E 's/\<[[:xdigit:]]{8}([[:xdigit:]]{0,7})\>/00000000\1/g' <<END
abcdef12cade 12345678 abcdefba12345678 12345 123456789
END
00000000cade 00000000 abcdefba12345678 12345 000000009

Where, \< and \> are word boundaries, and [:xdigit:] matches a hex digit.

1

The g at the end make sed repeat the substitution as many times as possible on the line. You only want to do it twice.

Let's do that with GNU awk:

echo 'abcdef12cade 12345678 abcdefba12345678' |
awk '{ sub("[0-9a-fA-F]{8}", "00000000", $1)
       sub("[0-9a-fA-F]{8}", "00000000", $2)
       print }'

This performs the substitution on the two first whitespace-delimited fields only, and then prints the resulting line.

4
  • OP didn't want the second match replaced though? Commented Jun 21, 2018 at 16:10
  • @DopeGhoti Their expected output is 00000000cade 00000000 abcdefba12345678, which is what this produces. Commented Jun 21, 2018 at 16:44
  • @DopeGhoti ... and I didn't read the title of the question until now, which leaves me more than slightly confused. Commented Jun 21, 2018 at 17:03
  • Yeah, the actual prose, title, and expected output presented are all somewhat contadictory. Commented Jun 21, 2018 at 17:30

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.