Archive

Archive for May, 2013

sed – Add 0 values to records in an existing file

May 7, 2013 Leave a comment

Just noting this here for future reference.

Problem:
The full problem is stated here. This is just a simplified version.

Input:

N/A124 14 0.8 1051670971100000
N/A125 15 0.8 1051670971100001
N/A126 16 0.8 1051670971100002
N/A127 17 0.8 1051670971100003

Output:

N/A124000014 0.8 1051670971100000
N/A125000015 0.8 1051670971100001
N/A126000016 0.8 1051670971100002
N/A127000017 0.8 1051670971100003

Solution:
There were other solutions but this one with sed caught my attention.

$ echo "N/A124    14 0.8    1051670971100000
N/A125    15 0.8    1051670971100001
N/A126    16 0.8    1051670971100002
N/A127    17 0.8    1051670971100003" | \
sed ":a; s/^\(.\{6,11\}\) /\10/; ta;"
N/A124000014 0.8    1051670971100000
N/A125000015 0.8    1051670971100001
N/A126000016 0.8    1051670971100002
N/A127000017 0.8    1051670971100003

This is what I think sed is doing. (Please correct me if I’m wrong)
:a – Create a label
s/^\(.\{6,11\}\) /\10/ – Group the first 6 to 11 characters, Substitute the match (ie first 6 to 11 characters, with the captured match and a zero)
ta – If the substitution was successful then branch to label a

t label
If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script.

`\{I,J\}’
Matches between I and J, inclusive, sequences.

Source:
http://www.unix.com/shell-programming-scripting/223047-add-0-values-replace-empty-value.html

Categories: bash, sed Tags: