I've been creating new folder with a specific naming pattern in the Terminal.
A folder named /dayX-title
that contains a README.md
file.
E.g: /codingclub/challenge/dayX-title/README.md
linxea at tmo in ~/codingclub/challenge
$ ls
day0-the-beginning-of-the-coding-club
day1-may-the-odds-be-in-your-favour
day2-so-far-so-good
day3-oh-man
This is how I create a new file in a new folder. I manually look through the list of folders to get the next count. Then type the title-with-dash-and-dash-and-dash.
$ touch day4-time-to-automate/README.md
I'm getting lazy so we'll write a bash script to do that.
I'm looking to write a commmand ./new time to automate
to create /day4-time-to-automate
with a README.md in it.
Steps:
- Iterate through all the folders
- Find the largest number of day
- Create a new folder with a README.md file with the given input filename
#!/bin/bash
# Take in all arguments in one variable
input="$*"
folderTitle=$input
# Check if there is input, otherwise exit script
if [[ -z "${folderTitle// }" ]]; then
echo "Where is your awesome title yo?"
exit 1
fi
# Replace space to -
folderTitle=${folderTitle// /-}
# Loop through the list of directories and find the biggest number
biggestNumber=-1
for dir in $(ls)
do
number=`sed 's/[^0-9]//g' <<< $dir`
if (( number > biggestNumber )); then
biggestNumber=$number
fi
done
# Increment the biggest number by 1
((biggestNumber=biggestNumber+1))
# Create a new folder and README.md file
newName=day$biggestNumber-$folderTitle
mkdir -p $newName
echo -e "TITLE: Day $biggestNumber $input\n" > $newName/README.md
# Print success message to make me feel good
echo Created $newName yo 🦄
Tada, now you just have to make the script executable by running chmod -x
and run the command ./new.sh
with title after that.
$ chmod -x new.sh # make the script executable
$ ./new.sh as usual this task takes longer than i expected
Uploaded my script to Repl.it, check it out at https://repl.it/@linxea/Create-New-Folder-and-File . You may need to login to play with it.
DOES IT WORTH THE TIME TO PICK UP BASH TO AUTOMATE SUCH A TINY MATTER?
a tiny yes.
Another Problem Another Day to Solve,
I wanted to extract the number 123
between day123-title-that-may-contain-123
using sed
but regex is messing with my mind. 🤯 How do I do that? How to I write a regex that only returns number between day
and -everything-else-after-dash
? Explain regex like I'm 5 please.
Top comments (0)