aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/tools/sed.md
blob: 5b5f74182335478966f3ba23ea3fd77d22f8b88c (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# sed(1)

```
sed [opts] [script] [file]
  opts:
    -i          edit file in place
    -i.bk       edit file in place and create backup file
                (with .bk suffix, can be specified differently)
    --follow-symlinks
                follow symlinks when editing in place
    -e SCRIPT   add SCRIPT to commands to be executed
                (can be specified multiple times)
    -f FILE     add content of FILE to command to be executed

    --debug     annotate program execution
```

## Examples
### Delete lines
```sh
# Delete two lines.
echo -e 'aa\nbb\ncc\ndd' | sed '1d;3d'
# bb
# dd

# Delete last ($) line.
echo -e 'aa\nbb\ncc\ndd' | sed '$d'
# aa
# bb
# cc

# Delete range of lines.
echo -e 'aa\nbb\ncc\ndd' | sed '1,3d'
# dd

# Delete lines matching pattern.
echo -e 'aa\nbb\ncc\ndd' | sed '/bb/d'
# aa
# cc
# dd

# Delete lines NOT matching pattern.
echo -e 'aa\nbb\ncc\ndd' | sed '/bb/!d'
# bb
```

### Insert lines
```sh
# Insert before line.
echo -e 'aa\nbb' | sed '2iABC'
# aa
# ABC
# bb

# Insert after line.
echo -e 'aa\nbb' | sed '2aABC'
# aa
# bb
# ABC

# Replace line.
echo -e 'aa\nbb' | sed '2cABC'
# aa
# ABC

# Insert before pattern match.
echo -e 'aa\nbb' | sed '/bb/i 123'
# aa
# 123
# bb
```

### Substitute lines
```sh
# Substitute by regex.
echo -e 'aafooaa\ncc' | sed 's/foo/MOOSE/'
# aaMOOSEaa
# cc
```

### Multiple scripts
```sh
echo -e 'foo\nbar' | sed -e 's/foo/FOO/' -e 's/FOO/BAR/'
# BAR
# bar
```

### Edit inplace through symlink
```sh
touch file
ln -s file link
ls -l link
# lrwxrwxrwx 1 johannst johannst 4 Feb  7 23:02 link -> file

sed -i --follow-symlinks '1iabc' link
ls -l link
# lrwxrwxrwx 1 johannst johannst 4 Feb  7 23:02 link -> file

sed -i '1iabc' link
ls -l link
# -rw-r--r-- 1 johannst johannst 0 Feb  7 23:02 link
```