Making substring with sed

Input:

You can easily do this by highlighting your code.

How can i get the substring from index 9 to 12 using sed?

$ sed "s/.\{8\}\(....\).*/\1/" file1
easi

Ok,how to get substring from index 0 to index 15?

Aptly:

$ sed "s/\(.\{16\}\).*/\1/" file1
You can easily

I take 0 to 15 to mean 16 characters.

1 Like

If i remove .* from the command then output is the original input string.Why is it?

sed "s/\(.\{16\}\)/\1/" file1

If you remove the ".*" part from the regex, that means you want to match a line that has only 16 characters, this simply does not match anything, so the original string is output.

=======================
I am sorry, my understanding was wrong.

1 Like
[2addr]s/regular expression/replacement/flags
             Substitute the replacement string for the first instance of the regular expression in the pattern space.

If you leave out the .* then it isn't part of the regular expression (and won't be in the pattern space), and so won't get substituted.

Output is the original, but it was still substituted:

i.e. consider:

$ sed "s/\(.\{16\}\)/X /" file1
X o this by highlighting your code.
1 Like