~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ ~~
⚙️ Discover my series on Automation of cybersecurity measures | Coded.
🔒 Related Stories: Insects | AWS Security | security code
💻 Free content on Cybersecurity Jobs | ✉️ Register for Broadcast list
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ ~~
When trying to parse errors and chunks of logs or information in bash scripts, I often find myself using cut. I thought I’d write a quick summary of how this command works here.
The cut command allows you to obtain a piece of string based on a delimiter. Here’s the gist of it.
A delimiter can be any character such as a comma. This is the character that separates the parts of the string you want to display in an on-screen display variable.
Let’s say you have a value like this:
apples,organges,bananas
The delimiter is the comma.
Let’s say you want to remove the “apples” from this chain.
Set the variable to the value:
fruits="apples,oranges,bananas"
Echo the value on screen:
echo $fruits
Add a pipe character after the echo command that allows us to send the output of this command to another command:
echo $fruits |
Now we will add the cut command to get the value after the first comma.
- Add order (cut)
- Add the delimiter by adding -d followed by the single character in quotes that is the delimiter.
- Add -f which indicates the fields you want to return.
- Add the field number (2) you want to return.
echo $fruits | cut -d "," -f2
What if you want to get the string “apples, bananas”? Well, you want fields 2 and three so:
cut -d "," -f2-3
But you can also just get all fields from 2 until the end.