MikeH
MikeH

Reputation: 59

Limiting SED to the first 10 characters of a line

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.

Upvotes: 6

Views: 5141

Answers (4)

Joseph Quinsey
Joseph Quinsey

Reputation: 9962

I think the shortest solution, and perhaps the simplest, is provided by sed itself, rather than awk[ward]:

 sed "h;s/-/:/g;G;s/\(..........\).*\n........../\1/"

Explanation:

  • (h) copy everything to the hold space
  • (s) do the substitution (to the entire pattern space)
  • (G) append the hold space, with a \n separator
  • (s) delete the characters up to the tenth after the \n, but keep the first ten.

Some test code:

 echo "--------------------------------" > foo
 sed -i "h;s/-/:/g;G;s/\(..........\).*\n........../\1/" foo
 cat foo
 ::::::::::----------------------

Upvotes: 2

frankc
frankc

Reputation: 11473

I'm not sure how make sed do it per se, however, I do know that you can feed sed the first 10 characters then paste the rest back in, like so:

paste -d"\0" <(cut -c1-10 $DPath/named.query.log | sed 's/\-/:/g') <(cut -c11- $DPath/named.query.log)

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203684

It's [almost always] simpler with awk:

awk '{target=substr($0,1,10); gsub(/-/,":",target); print target substr($0,11)}' file

Upvotes: 3

Florin Stingaciu
Florin Stingaciu

Reputation: 8285

You can do the following:

cut -c 1-10 $DPath/named.query.log | sed -i 's/-/:/g'

The cut statemnt takes only the first 10 chars of each line in that file. The output of that should be piped in a file. As of now it will just output to your terminal

Upvotes: 0

Related Questions