SED limit to first 10 characters of a line

I run sed as part of a shell script to clear the bind logs to insert into the database.

One of the sed commands:

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

This turns out to be problematic, as it interrupts any resource requests that also include dashes (I use: as a delimiter for the awk statement next).

My question is: how to limit the sed command above to only the first ten characters of a string? I have not seen a specific switch that does this, and I'm nowhere good enough for RegEx to even start developing one that works. I cannot just use a regular expression to match previous numbers, because it is possible that the template may be part of a resource request. Hell, I can't even use pattern matching for #### - ## - ## because, again, it can be part of the resource.

Any ideas are greatly appreciated.

+6
source share
4 answers

This is [almost always] simpler with awk:

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

I think the shortest solution, and possibly the simplest, is provided by sed itself, not awk [ward]:

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

Explanation:

  • (h) copy everything on hold.
  • (s) perform a lookup (in the entire template space)
  • (G) add hold space with delimiter \n
  • (s) delete characters to the tenth after \n , but keep the first ten.

Some test codes:

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

I'm not sure how to make sed by itself, however I know that you can feed the family of the first 10 characters and then insert the rest back, for example:

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

+1
source

You can do the following:

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

The abbreviated statemnt accepts only the first 10 characters of each line in this file. The output should be transferred to a file. At the moment, it will simply be displayed on your terminal

0
source

All Articles