61 lines
No EOL
2.4 KiB
Markdown
61 lines
No EOL
2.4 KiB
Markdown
sed example
|
|
|
|
|
|
theory
|
|
grep is powerful along with other unix tools like cut xargs head less etc.
|
|
awk goes line by line in a file/stdin giving you all the words in variables with like $1 $2 $3 which you can use however you want
|
|
|
|
To achieve this using `sed` (Stream Editor), you can use a regular expression pattern to match the text you want to modify and then replace it with the desired output.
|
|
|
|
Assuming you want to remove the `.md` from occurrences of patterns like `(sdusyd.md)` within a file and considering your example, we use the following `sed` command:
|
|
|
|
```bash
|
|
sed 's/\(([^)]*)\).md/\1/g' file.txt
|
|
```
|
|
|
|
Here's a breakdown of the command:
|
|
|
|
- `sed`: The command to call Stream Editor.
|
|
- `s/pattern/replacement/`: The substitute command, where `pattern` is the regex pattern you are looking to match, and `replacement` is the text you want to use to replace the matched pattern.
|
|
- `\(([^)]*)\).md`: This is the regex pattern we are matching.
|
|
- `\(`: Matches the literal character "(".
|
|
- `([^)]*)`: Matches and captures any character except `)` zero or more times. This corresponds to your `<string>`.
|
|
- `\)`: Matches the literal character ")".
|
|
- `.md`: Matches the string `.md` that we intend to remove.
|
|
- `\1`: Refers to the first captured group from the match. In this case, it's the string matched by `([^)]*)`, which is `<string>`.
|
|
- `g`: Global flag to perform the replacement for all occurrences within a line.
|
|
- `file.txt`: The file in which the replacements should occur.
|
|
|
|
|
|
For example, if `file.txt` contains:
|
|
|
|
```text
|
|
Some text (sdusyd.md) with markdown files and another (anotherfile.md).
|
|
```
|
|
|
|
After running the command, it will output:
|
|
|
|
```text
|
|
Some text (sdusyd) with markdown files and another (anotherfile).
|
|
```
|
|
|
|
**Note**: If you want to directly modify the file (instead of just outputting the modified text to the terminal), you can use the `-i` option for in-place editing with `sed`. Just remember to backup your original files before using `-i`, as it overwrites the original file:
|
|
|
|
```bash
|
|
sed -i 's/\(([^)]*)\).md/\1/g' file.txt
|
|
```
|
|
|
|
This will change `file.txt` in-place.
|
|
|
|
- same thing with perl
|
|
`perl -pe 's/\(([^()]+)\.md\)/\($1\)/g' file.txt` : this will only print output without modifying file
|
|
`perl -pi -e 's/\(([^()]+)\.md\)/\($1\)/g' test.txt` : this will modify file too
|
|
|
|
this worked for me
|
|
```bash
|
|
sed -E -i 's/\(([^\)]*)\.md\)/\(\1\)/g' file.txt
|
|
```
|
|
|
|
|
|
replicating grep with awk
|
|
`history | awk '/cd/'` will replicate3 `history | grep 'cd'` |