BashWars
How to build bash oneliners
grep
Search string without case sensative
grep -i 'example' input.txtCounting the number of matches
grep -c 'example' input.txtSearch with regex
grep -E 'example[0-9]+' input.txtPrinting strings without matches
grep -v 'example' input.txtcut
Retrieving characters in a range
To extract the fifth through tenth characters from each string:
cut -c 5-10 input.txtExtracting fields using a delimiter
To extract the second field, where the fields are separated by commas:
sort
Sort strings alphabetically
To sort strings in reverse order:
Sorting numeric values
Removing duplicates when sorting
uniq
Remove duplicate strings
Count duplicate strings
tr
Replacing characters
To replace all colons to spaces:
Remove characters
To remove all numbers:
Case conversion
To convert all lowercase letters to uppercase:
head & tail
Printing the first N lines
To print first 10 strings in file:
Printing the last N lines
To print last 10 strings in file:
xargs
Passing arguments to a command
To pass a list of files to the rm command:
Limiting the number of arguments
To pass only two arguments at a time:
Applying a command in parallel
To execute a command in parallel on each file:
find
Find file by name
To search for all files named file.txt in the current directory and subdirectories:
Find file by size
To search for all files larger than 1 MB:
3. Find and execute command
To delete all file with .tmp extension:
wc
Count strings in file
Count word in file
Count symbols in file
AWK
Take info from output by column
Count strings in file
Delete empty strings in file
Sum column values
To sum the values โโin a specific column (for example, the third column):
Counting unique values โโin a column
To count the number of unique values โโin the first column:
sed
Replacing text
To replace all occurrences of the word "oldtext" with "newtext":
Delete strings
To delete lines containing a specific word, such as "delete":
Inserting text after a line
To insert the line "Inserted text" after each line containing the word "pattern":
To insert the line "Inserted text" before each line containing the word "pattern":
Replace text only on certain lines
To replace the text "oldtext" with "newtext" only on lines containing the word "pattern":
Removing the first N rows
To remove the first 5 lines from a file:
Printing Specific Strings
To output lines 10 to 20:
jq
Format string to json
Retrieving a value by key
To extract the value for the name key from JSON:
To retrieve a value from a nested key name.age:
Filtering array elements
To filter array elements where the age field is greater than 30:
JSON structure conversion
To change the JSON structure, for example to output only the name and age:
Retrieving all values โโof a specific key
To retrieve all id key values โโfrom an array of objects:
Counting elements in an array
To count the number of elements in the items array:
Replacing values โโin JSON
To replace all status key values โโwith active:
Last updated