I thought I’ll make this thread for all of you out there who have questions but are afraid to ask them. This is your chance!
I’ll try my best to answer any questions here, but I hope others in the community will contribute too!
I thought I’ll make this thread for all of you out there who have questions but are afraid to ask them. This is your chance!
I’ll try my best to answer any questions here, but I hope others in the community will contribute too!
Maybe not a super beginner question, but what do awk and sed do and how do I use them?
This is 80% of my usage of awk and sed:
“ugh, I need the 4th column of this print out”:
command | awk '{print $4}'
Useful for getting pids out of a
ps
command you applied a bunch ofgrep
s to.”hm, if I change all ‘this’ to ‘that’ in the print out, I get what I want":
command | sed "s/this/that/g"
Useful for a lot of things, like “I need to change the urls in this to that” or whatever.
Basically the rest I have to look up.
I say that covers around 99% of the awk/sed I use.
I was gonna write 99%, but then I remember I also need capture groups quite often. That would make 99% I’d say
Awk lets you do operations based on patterns. You can make little scripts and mini programs with it.
Sed lets you edit streams.
Almost everything can be treated like a stream so with those two tools you have the power to do damn near everything ever.
There’s a book called sed & awk that’s real good.
Awk is a programming language designed for reading files line by line. It finds lines by a pattern and then runs an action on that line if the pattern matches. You can easily write a 1-line program on the command line and ask Awk to run that 1-line program on a file. Here is a program to count the number of “comment” lines in a script:
It is a good way to inspect the content of files, espcially log files or CSV files. But Awk can do some fairly complex file editing operations as well, like collating multiple files. It is a complete programming language.
Sed works similar to Awk, but it is much simplified, and designed mostly around CLI usage. The pattern language is similar to Awk, but the commands are usually just one or two letters representing actions like “print the line” or “copy the line to the in-memory buffer” or “dump the in-memory buffer to output.”
If you’re gonna dive into sed and awk, I’d also highly recommend learning at least the basics of regular expressions. The book Mastering Regular Expressions has been tremendously helpful for me.
Edit: a letter. Stupid autocorrect.