aboutsummaryrefslogtreecommitdiff
path: root/bin/trs.awk
blob: fbb7eeba2ed657e1259c18b1ecec9207f39a752f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Substitute one string for another in input (no newlines, no regex)
BEGIN {
    # Name self
    self = "trs"

    # Two and only two arguments required
    if (ARGC != 3)
        fail("Need a string and a replacement")

    # Get arguments and blank them so awk doesn't try to read them as files
    str = ARGV[1]
    rep = ARGV[2]
    ARGV[1] = ARGV[2] = ""

    # String length is relevant here
    if (!(len = length(str)))
        fail("String to replace cannot be null")
}

# Bailout function
function fail(msg) {
    stderr = "cat >&2"
    printf "%s: %s\n", self, msg | stderr
    close(stderr)
    exit(2)
}

# Run on each line
{
    lin = ""
    for (buf = $0; ind = index(buf, str); buf = substr(buf, ind + len))
        lin = lin substr(buf, 1, ind - 1) rep
    lin = lin buf
    print lin
}