Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting SED to the first 10 characters of a line

Tags:

bash

sed

I'm running sed as a part of a shell script to clean up bind logs for insertion into a database.

One of the sed commands is the following:

sed -i 's/-/:/g' $DPath/named.query.log

This turns out to be problematic as it disrupts any resource requests that also include a dash (I'm using : as a delimiter for an awk statement further down).

My question is how do I limit the sed command above to only the first ten characters of the line? I haven't seen a specific switch that does this, and I'm nowhere near good enough with RegEx to even start on developing one that works. I can't just use regex to match the preceding numbers because it's possible that the pattern could be part of a resource request. Heck, I can't even use pattern matching for ####-##-## because, again, it could be part of the resource.

Any ideas are much appreciated.

like image 804
MikeH Avatar asked Nov 21 '12 19:11

MikeH


People also ask

How do you display the first 10 characters from each line of a file?

The head command is used to display the first lines of a file. By default, the head command will print only the first 10 lines. The head command ships with the coreutils package, which might be already installed on our machine. Mind that newlines, tabs, and spaces are also counted as bytes.

How do I remove the first 10 characters from a string in Unix?

To remove the first n characters of a string, we can use the parameter expansion syntax ${str: position} in the Bash shell. position: The starting position of a string extraction.


1 Answers

It's [almost always] simpler with awk:

awk '{target=substr($0,1,10); gsub(/-/,":",target); print target substr($0,11)}' file
like image 115
Ed Morton Avatar answered Sep 27 '22 16:09

Ed Morton