barras
barras

Reputation: 83

sed - match regex in specific position

I'm having some trouble creating a one liner or a simple script to edit some fixed length files using sed.

Supposing my file has lines in this format:

IPITTYTHEFOOBUTIDONOTPITTYTHEBAR

IPITTYTH BARBUTIDONOTPITTYTH3FOO

If the entire lines are considered as a string, I can say I would want to match the substring that starts in position 10 and has length 3 with a regex. If it matches the regex I want to had some other string in the end of that line.

Assuming the matching regex is B.R, and the string to append in the end of the line is NOT, I would want my file to turn into:

IPITTYTHEFOOBUTIDONOTPITTYTHEBAR

IPITTYTH BARBUTIDONOTPITTYTHEFOONOT

The lines in the files are bigger than the ones in this sample.

So far I have this:

sed -i '/B.R/ s/$/NOT/' file.name

The problem is that this ignores the position where the regex is matched, making the first line of the example a match as well:

IPITTYTHEFOOBUTIDONOTPITTYTHEBAR

IPITTYTH BARBUTIDONOTPITTYTH3FOO

I'm open to use awk as well.

Thanks in advance.

Upvotes: 0

Views: 2330

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174776

You are almost there. You just need to specify the characters which exists before B.R . If B is at 10th position then there must be 9 characters exists before B

sed -i '/^.\{9\}B.R/s/$/NOT/' file.name

Example:

$ sed  '/^.\{9\}B.R/s/$/NOT/' file
IPITTYTHEFOOBUTIDONOTPITTYTHEBAR
IPITTYTH BARBUTIDONOTPITTYTHEFOONOT

Upvotes: 4

Related Questions