The terminal is extremely powerful and it is now my topmost choice in coding. Here are some useful commands for common tasks that will hopefully help appreciate the power of the command line!
- List files sorted by time
ls -lt
- List of files sorted by size
ls -alS
- List of files from s3 ... only name:
s4cmd ls s3://tempbin/ | grep zerod_archive_ | awk '{print $NF}' | head
- List of files from s3 AND download them in one command:
for i in
s4cmd ls s3://tempbin | grep zerod_archive_ | awk '{print $NF}'; do s3cmd get $i ; done
- List files above a certain size:
find . -size +10k -exec ls -lh {} \+
- Credit: https://stackoverflow.com/a/13282838/644081
- List files in directory and upload all to s3 using
s3cmd
- List only files in directory and count them
ls -p | grep -v / | wc -l
- List
ls -l
only certain columns- first and last column
ls -l *.sh | sed 's/|/ /' | awk '{print $1, $9}'
- only last column
ls -l *.sh | sed 's/|/ /' | awk '{print $9}'
- first and last column
- Create a folder using a pattern. Pretty cool!
mkdir -p /usr/local/etc/nginx/sites-{enabled,available}
- List files and pipe to copy
ls *.txt | tail -5 | xargs cp -t /media/ramdisk/
- Look at
fish
shell historysublime ~/.local/share/fish/fish_history
- credit: https://fishshell.com/docs/current/index.html#history-search
for i in `ls -al | grep zerod_archive_ | awk '{print $NF}'` ; do s3cmd put $i s3://tempbin/zerod_final/ ; done
-
Find a file in bash
find . -type f -name '*aad*.pdf'
- Source: http://www.cyberciti.biz/faq/howto-find-a-file-under-unix/
-
Find all zip files in a directory and delete them
find . -name '*.zip' | xargs rm
-
Find a directory or folder in bash with a certain name
find . -name oknpjjbmpnndlpmnhmekjpocelpnlfdi -type d
-
Finding files on a Mac OSX with a fuzzy file name
mdfind 'kMDItemDisplayName == "*flickr*.js"c'
-
Finding files with a -ve grep
mdfind 'kMDItemDisplayName == "*sequelize*.js"c' | grep -v node_modules
-
List only directories
ls -d */
-
Find size of directories
du -sh *
-
Find disk utilization
df -h
-
Download zip file with curl command
curl -LOk
curl -LOk -X 'GET' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:51.0) Gecko/20100101 Firefox/51.0' -H 'Referer: https://nseindia.com/products/content/equities/equities/archieve_eq.htm' -H 'Upgrade-Insecure-Requests: 1' 'https://nseindia.com/content/historical/EQUITIES/2000/MAR/cm7MAR2000bhav.csv.zip'
-
Count number of lines in a file
wc -l mytextfile
-
Count number of files in a directory
cd directory_to_count ls | wc -l
-
Find or search text in files in recursively from the command line
grep -R 'analyze' **/*.html
grep -RF 'analyze' **/*.html
- Credit: https://seesparkbox.com/foundry/demystifying_multi_file_searches_in_vim_and_the_command_line
- Faster search using
ag
:ag analyze . -l -G .html
searches for wordanalyze
across.html
files - http://conqueringthecommandline.com/book/ack_ag#cid18
-
Find lines in a text file that contain a certain word
grep -w GAL Model_GFD-Top-5-Stocks-Prev-Day.Rout
grep -i GAL Model_GFD-Top-5-Stocks-Prev-Day.Rout
-
Rename all files in a directory
for f in * ; do mv "$f" "$f.mp3" ; done
- This needs
bash
... doesn't seem to work infish
- Run the below in bash:
for FILE in *; do # Strip of any extension, and save to FILE2 FILE2=${FILE%\.*} # If it's the same afterward, then there was no extension - rename it if [ "$FILE" = "$FILE2" ]; then mv "$FILE" "$FILE.mp3" fi done
-
Zip an entire directory
zip -r tobwis.zip tobwis/
-
Moving files in a folder in parallel using
rsync
msrsync -p 20 --progress /Users/santosh/Dropbox/ /Volumes/Seagate-Slim/mac-air-2015/Dropbox/
msrsync -p10 --rsync "-a --remove-source-files --progress" /Users/santosh/Dropbox/ /Volumes/Seagate-Slim/mac-air-2015/Dropbox/
cd ~
rm /Users/santosh/transfer.log
rm /Users/santosh/result.log
# build the dry-run list
rsync -avzm --stats --safe-links --ignore-existing --dry-run \
--human-readable /Users/santosh/Dropbox/ /Volumes/Seagate-Slim/mac-air-2015/Dropbox/ > /Users/santosh/transfer.log
cd /Users/santosh/Dropbox/
# transfer them!
cat /Users/santosh/transfer.log | \
parallel --will-cite -j 20 rsync -avzm --progress --relative \
--stats --safe-links --remove-source-files --ignore-existing \
--human-readable {} /Volumes/Seagate-Slim/mac-air-2015/Dropbox/ > result.log
- Copying / Moving files between folders using rsync
- http://www.cyberciti.biz/faq/show-progress-during-file-transfer/
rsync -a --remove-source-files --progress /Users/santoshsrinivas/Pictures/Photos\ Library.photoslibrary/Masters/ /Users/santoshsrinivas/Pictures/Picasa/
- Copying files using rsync in parallel
# credit: https://unix.stackexchange.com/questions/189878/parallelise-rsync-using-gnu-parallel
# build the dry-run list
rsync -avzm --stats --safe-links --ignore-existing --dry-run \
--human-readable /Users/santosh/ /Volumes/Backup\ Plus/mac-backup/ > /Users/santosh/transfer.log
# transfer them!
cat /Users/santosh/transfer.log | \
parallel --will-cite -j 20 rsync -avzm --relative \
--stats --safe-links --ignore-existing \
--human-readable {} /Volumes/Backup\ Plus/mac-backup/ > result.log
- use a modified tool jbd/msrsync: Multi-stream rsync wrapper
./msrsync -p 20 --progress /Users/santosh/ /Volumes/Backup\ Plus/mac-backup/
- Batch resize multiple images with a single command
mogrify -resize "800x230>" *.jpg
mogrify -monitor -write "resize.jpg" -resize "^800x230" dreamstimefree_15333415\ \(1\).jpg
- Source: ImageMagick: Command-line Tools: Mogrify
sharp --verbose --width 800 -o dest/ fogpics/*
- Source: sharp-cli
- Resize and crop using:
sharp --verbose --crop --width 800 --height 230 -o dest/ fogpics/*
- Resize movie to small screen size
ffmpeg -i IMG_5137.MOV -vf scale=320:-2 IMG_5137_320.MOV
- Sync s3 bucket with local folder:
aws s3 sync s3://tempbin/peloton_digital/ peloton_digital/
- Downloading file to disk using lynx
- Downloading file using lynx is very confusing! Solution: Press
D
to download the file to the disk. Once the file has been downloaded, you will be asked the location to save at the end! Have patience :-)
- Downloading file using lynx is very confusing! Solution: Press
- Starting a simpleHTTPserver using python
python -m SimpleHTTPServer
python -m http.server 8083
- Convert video files for Apple devices using handbrake cli
- Replacing text from the command line
ack -o '(?<=track:).*?(?=\"\s\|\sUser:)' songs.txt > songs-final.txt
- Kill all zombie processes in a loop
- http://askubuntu.com/questions/111422/how-to-find-zombie-process
ps axo pid=,stat= | awk '$2~/^Z/ { print }'
- Kill a meteor-tool process
- kill -9
ps ax | grep meteor-tool | awk '{print $1}'
- Credit: https://gist.github.com/light9/6870997
- kill -9
- Add to
fish
path
set -U fish_user_paths ~/anaconda/bin $fish_user_paths
set -U fish_user_paths ~/mongodb/bin $fish_user_paths
- Credit: http://stackoverflow.com/questions/34280113/add-conda-to-path-in-fish
- Shutdown a system after say 3 hrs
sudo shutdown -h +180
- Shutdown after 8 hrs
Echo "sudo shutdown -h 00:00"|at now +8 hours
- Generate an iso date
echo $(date --iso-8601=seconds)
- Detach a
tmux
session from a smaller client usingCtrl-b + D
- http://stackoverflow.com/questions/7814612/is-there-any-way-to-redraw-tmux-window-when-switching-smaller-monitor-to-bigger
- If you are doing it in an active tmux session, just press
CTRL+B
(or whichever your custom tmux command) then:detach -a
for pid in $(ps axo pid=,stat= | awk '$2~/^Z/ { print $1 }') ; do
echo $pid;
sudo kill $pid; # do something interesting here
done
-
Push all local branches to origin (Credit: https://stackoverflow.com/questions/6865302/push-local-git-repo-to-new-remote-including-all-branches-and-tags)
git push origin --all
-
Pull all remote branches to local
git fetch --all
-
Find hostname from mac osx term
smbutil status 10.0.0.19
arp -a
... seems to list all connected devices on network- Credit: https://discussions.apple.com/thread/4308987?start=0&tstart=0
-
List files and pipe a grep to delete the file using rm
ls | grep "(1)" | xargs rm
-
Delete hidden files BEFORE git repo commit
git status | grep "/._" | xargs rm
-
Move a huge number of files from one directory to another:
for file in "/Users/santoshsrinivas/PIBMac53/541385/data/archive/"*.csv; do mv -- "$file" "/Users/santoshsrinivas/PIB_Data/"; done
Changing the editor to edit a file
Sometimes, you want to use a different editor while editing a file. So here is the trick from my fish shell.
The below script will change my editor to vim and allow me to edit crontab.
bash
export EDITOR=vim
crontab -e
- netstat -ln | awk '/mysql(.*)?.sock/ { print $9 }'
- Get list of all running docker container IPs
- 10 Examples of how to get Docker Container IP Address
- In bash
docker inspect --format '{{ .NetworkSettings.IPAddress }}' $(docker ps -q)
- In bash
- 10 Examples of how to get Docker Container IP Address
- Data Munging for Docker lists
-List docker containers without the header
-
docker ps | awk '{if(NR>1) print $NF}'
-docker stats $(docker ps | awk '{if(NR>1) print $NF}')
-docker inspect $(docker ps | awk '{if(NR>1) print $1}')
-docker inspect --format '{{ .NetworkSettings.IPAddress }} ' $(docker ps | awk '{if(NR>1) print $1}')
-docker inspect --format '{{ .Id }} {{ .NetworkSettings.IPAddress }} {{ .Name }}' $(docker ps | awk '{if(NR>1) print $1}')
-Credit: http://askubuntu.com/questions/699508/how-to-extract-mapped-ports-from-docker-pss-output -http://container42.com/2016/03/27/docker-quicktip-7-psformat/ -docker ps --format "{{.ID}}: {{.Ports}} {{.Names}}"
- Remove password protection from pdf
gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=unencrypted.pdf -c .setpdfwrite -f encrypted.pdf
- Use this: https://github.com/jakepetroules/littlebirdy
- Unzip into a folder
unzip /path/to/file.zip -d temp_for_zip_extract
-
Run R script in terminal using
R CMD BATCH --no-save --no-restore "Read-NSE_CM_EOD_Bhavcopy.R"
R CMD BATCH --no-save --no-restore "Analysis-EOD-Data-Setup.R"
-
Create shortcut to ripgrep:
ln -s "/Users/santosh/tools/ripgrep/rg" /usr/local/bin/rg
-
Put a folder recursively
s3cmd put -r LM s3://tempbin/LM/
- Need to start to "BODYPUMP 100 XXX"
- BETTER:
s3cmd sync -v LM --skip-existing s3://tempbin/LM/
- Try this first:
s3cmd sync --dry-run --skip-existing --delete-removed -v s3://tempbin/LM/ LM/
-
In DO folder run:
mv *.mp4 LM/
s3cmd put -r LM s3://tempbin/LM/
rm LM/*.mp4
- Playing with s3cmd output to get only the filenames
#!/bin/bash
# Blog at https://www.santoshsrinivas.com/text-manipulation-on-the-command-line/
awk '{$1=""; $2=""; $3=""; print}' lm-1.txt > lm-1-files.txt
awk -F"s3://tempbin/LM/LM/" '{ print $2}' lm-1-files.txt > lm-2-files.txt
I'm thinking of using sshfs
to sync my remote ubuntu machine disk a local mounted folder on my mac.
To replicate the folder:
sshfs ghost@3.85.118.126://home/ghost/Dropbox/pandora/My-Projects/repos/dalalbeat/python/ ~/ec2_db/python
If I choose to rsync
- Conquering the command line