Commands using printf (206)

  • Uses soxi instead of mplayer


    0
    soxi -D * | awk '{SUM += $1} END { printf "%d:%d:%d\n",SUM/3600,SUM%3600/60,SUM%60}'
    hufman · 2017-04-08 17:37:03 15
  • All the other example fail when running in a folder containing too many files due to * being saturated. This command does not use *, allowing me to run it in one folder containing over 300000 audio files. As to running on so many files, I used GNU parallel in order to spawn as many processes as cores, tremendously fasting up the process. Show Sample Output


    0
    ls|grep ".wav"|parallel -j$(nproc) soxi -D {}|awk '{SUM += $1} END { printf "%d:%d:%d\n",SUM/3600,SUM%3600/60,SUM%60}'
    jupiter126 · 2017-05-02 21:37:24 20
  • Prints the variable "$a" 80 times with a new line at the end. There is no need for backspaces as printf (by default) does not print a newline nor an space. Use a bunch of variables called "$_0" and a number. The name start with an underscore and a 0 to avoid conflicts with already defined variables. If still worried: All variables may be cleared up before use with "unset $_{1..080}". A command with a variable count is a bit of a mouthful: a=hello+; n=7; eval printf "%s" '$_{1..0'"$n"'}"$a"' $'$\'\\n\'' And carry some risk if the variable "$n" could be set by an attacker. Show Sample Output


    0
    a=+; printf "%s" $_{1..080}"$a" $'\n'
    isaacmarcos · 2017-06-06 21:59:58 17
  • This is a bit of a bash hack to catch STDERR and append a log level to it. So for example, if your script has pseudo loglevels like so: echo "INFO - finding files" [ -f ${files} ] || echo "WARN - no files found" Any subcommands that write to STDERR will screw that up Adding 2> >(fb=$(dd bs=1 count=1 2>/dev/null | od -t o1 -A n); [ "$fb" ] && err=$(printf "\\${fb# }"; cat) && echo "ERROR - $err") to the command does the following: 2> Redirect STDERR >( Spawn a subshell (STDERR is then redirected to the file descriptor for this subshell) fb=$(....) get the first byte of input [ "$fb" ] test if there's a first byte && err=$(printf....) save the output to the $err variable && echo "ERROR - $err" append your pseudo loglevel and the error message Heavily borrowed from https://unix.stackexchange.com/questions/33049/check-if-pipe-is-empty-and-run-a-command-on-the-data-if-it-isnt Show Sample Output


    0
    [command] 2> >(fb=$(dd bs=1 count=1 2>/dev/null | od -t o1 -A n); [ "$fb" ] && err=$(printf "\\${fb# }"; cat) && echo "ERROR - $err")
    tyzbit · 2017-10-16 22:22:42 21
  • Compactly display a bitcoin-cli fee estimate in satoshis/Byte, sat/B, date time stamp. Change the 6 to the desired number of confirmations. Display in btc/KB unit of measure: printf %g "$(bccli estimatesmartfee 6 "ECONOMICAL" | jq .feerate)";printf " btc/KB estimated feerate for 6 confirmations\nMultiply by 100,000 to get sat/B\n"; Two settings for estimate mode are "ECONOMICAL". "CONSERVATIVE" is the same as "UNSET" # jq is a json filter. sudo apt-get install jq Show Sample Output


    0
    printf %g "$(bitcoin-cli estimatesmartfee 6 "ECONOMICAL" | jq .feerate*100000)";printf " sat/B estimated feerate for 6 confirmations as of $(date +%c)\nDivide by 100,000 to get btc/KB\n"
    deinerson1 · 2018-06-20 13:40:32 234
  • Use this function with bash version 4+ to convert arbitrary hexadecimal sequences to binary. If you don't have bash 4+ then modify the lowercase to uppercase demangling statement s=${@^^} to set s equal to the uppercase hex input or the bc command throws an input parser error. Show Sample Output


    0
    hex2bin () { s=${@^^}; for i in $(seq 0 1 $((${#s}-1))); do printf "%04s" `printf "ibase=16; obase=2; ${s:$i:1};\n" | bc` ; done; printf "\n"; }
    RiskNerd · 2018-10-02 22:02:33 341

  • 0
    printf %s\\n '"\en": "\e0\e."' '"\em": "\e1\e."' '"\e,": "\e2\e."'>>~/.inputrc
    lri · 2019-01-22 07:10:16 32
  • This shell calculator uses POSIX features only and is therefore portable. By default the number of significant figures is limited to 8 with trailing zeros stripped, resembling the display of a basic pocket calculator. You might want to increase this to 12 to emulate a scientific calculator. Show Sample Output


    0
    calc(){ printf "%.8g\n" $(printf "%s\n" "$*" | bc -l); }
    lordtoran · 2019-02-06 23:32:35 607
  • No need to fork off a process.


    0
    printf "%.s*" {1..40}; printf "\n"
    doododoltala · 2019-07-11 00:27:20 37
  • This “sysload” alias converts the load average to percentages and divides them by the number of CPUs/cores. It may provide a more intuitive guesstimate of how much work the server is doing. Show Sample Output


    0
    alias sysload='printf "System load (1m/5m/15m): "; for l in 1 2 3 ; do printf "%.1f%s" "$(( $(cat /proc/loadavg | cut -f $l -d " ") * 100 / $(nproc) ))" "% "; done; printf "\n"'
    lordtoran · 2021-03-27 17:10:53 150
  • Show temp of all disk with the drivetemp module activate Show Sample Output


    0
    grep -l "drivetemp" /sys/class/hwmon/hwmon*/name | while read f; do printf "%s(%-.2s°C)\n" "`<${f%/*}/device/model`" "`<${f%/*}/temp1_input`"; done
    kokoparkletal · 2023-09-10 18:24:29 80
  • This command adds the numbers 10, 12, 14 to a bunch of mp3's in the current working directory. You can then run the command replacing the inital i=10 with i=11 to add 11,13,15 in another directory then mv the files together and the first files interweave with the second group of files. I used this to weave a backlog of a podcast with other podcast so I didn't get sick of one while I was catching up. I started at 10 because printf blows up with 0 padded numbers 08 and 09 which kind of makes the printf command redundant as it was used to pad numbers 1 - 9 so they would come first and not get sorted incorrectly


    -1
    i=10;for o in *.mp3; do i=$(printf "%02d" $i); mv $o $i$o; ((i = $i + 2)); done
    bazzawill · 2009-04-13 12:33:52 7
  • There's no need for ls or grep; printf is builtin to most modern shells


    -1
    printf "%s\n" !(pattern) ## ksh, or bash with shopt -s extglob
    cfajohnson · 2009-11-26 14:09:56 3
  • So your boss wants to know how much memory has been assigned to each virtual machine running on your server... here's how to nab that information from the command line while logged in to that server Show Sample Output


    -1
    for file in $( vmrun list | grep 'vmx$' | sort ); do printf "% 40s %s M\n" $(echo "$( echo -n ${file}:\ ; grep memsize $file )" | sed -e 's/.*\///' -e 's/"//g' -e 's/memsize.=//'); done;
    linuxrawkstar · 2010-11-19 06:14:11 3
  • remove all carriage return of a given file (or input, if used with | ) and replace them with a space (or whatever character is after %s) Show Sample Output


    -1
    awk ' { printf ("%s ", $0)} END {printf ("\n") } ' FILE
    bouktin · 2011-02-02 11:51:41 6
  • The exported TSV file of Google Adwords' first five columns are text, they usually should collapse into one cell, a multi-line text cell, but there is no guaranteed way to represent line-break within cells for .tsv file format, thus Google split it to 5 columns. The problem is, with 5 columns of text, there are hardly space to put additional fields while maintain printable output. This script collapses the first five columns of each row into one single multi-line text cell, for console output or direct send to printer.


    -1
    awk -F $'\t' '{printf $1 LS $2 LS $3 LS $4 LS $5; for (i = 7; i < NF; i++) printf $i "\t"; printf "\n--\n";}' LS=$'\n' 'Ad report.tsv' | column -t -s $'\t'
    zhangweiwu · 2011-02-28 10:52:16 4
  • This command will delete all branches in your git repository other than next and master. I use this to cleanup my git repos after making multiple branches and merging them back into next. It's much faster than individually deleting each expired branch using: git branch -D <branch_name>


    -1
    git branch -D `git branch | awk '{ if ($0 !~ /next|master/) printf "%s", $0 }'`
    denheck · 2011-04-14 17:43:21 4
  • Group membership in OS X is a mish-mash of standards that end up meaning there's almost a half-dozen of ways to belong to a group, what with group inheritance and automatic assignment. This means there's no easy command to find out all groups a user belongs to. The only sensible way then is to list all users and then query each user for membership. NOTE: This is a function. Once input you can execute it by calling with a groupname. Show Sample Output


    -1
    members () { dscl . -list /Users | while read user; do printf "$user "; dsmemberutil checkmembership -U "$user" -G "$*"; done | grep "is a member" | cut -d " " -f 1; };
    eduo · 2012-05-20 11:34:33 7
  • I don't think it's possible to give a (background) colour to the tab itself, since a tab is, IIUC, simply a command to the terminal to move to the right. Nevertheless, this "highlighting" can be helpful when working with tab-separated files. Show Sample Output


    -1
    hl-nonprinting () { local C=$(printf '\033[0;36m') R=$(printf '\033[0m'); sed -e "s/\t/${C}&#9657;&$R/g" -e "s/$/${C}&#8267;$R/";}
    unhammer · 2012-11-07 09:55:48 4
  • Can't see it here, but the non-breaking space is highlighted :) Of course, cat -t -e achieves something similar, but less colourful. Could add more code points from https://en.wikipedia.org/wiki/Space_%28punctuation%29#Spaces_in_Unicode Show Sample Output


    -1
    hl-nonprinting () { local C=$(printf '\033[0;36m') B=$(printf '\033[0;46m') R=$(printf '\033[0m') np=$(env printf "\u00A0\uFEFF"); sed -e "s/\t/${C}&#9657;&$R/g" -e "s/$/${C}&#8267;$R/" -e "s/[$np]/${B}& $R/g";}
    unhammer · 2012-11-07 10:09:40 9

  • -1
    yes 'c=(" " " " " " 0 1); printf "${c[RANDOM%5]}"' | bash
    stx · 2013-11-09 16:10:41 6
  • Needs to be run in a battery sysfs dir, eg. /sys/class/power_supply/BAT0 on my system. Displays the battery's current charge and the rate per-second at which energy is {dis,}charging. All values are displayed as percentages of "full" charge. The first column is the current charge. The second is the rate of change averaged over the entire lifetime of the command (or since the AC cable was {un,}plugged), and the third column is the rate of change averaged over the last minute (controlled by the C=60 variable passed to awk). The sample output captures a scenario where I ran 'yes' in another terminal to max out a CPU. My battery was at 76% charge and you can see the energy drain starts to rise above 0.01% per-second as the cpu starts working and the fan kicks in etc. While idle it was more like 0.005% per-second. I tried to use this to estimate the remaining battery life/time until fully charged, but found it to be pretty useless... As my battery gets more charged it starts to charge slower, which meant the estimate was always wrong. Not sure if that's common for batteries or not. Show Sample Output


    -1
    while cat energy_now; do sleep 1; done |awk -v F=$(cat energy_full) -v C=60 'NR==1{P=B=$1;p=100/F} {d=$1-P; if(d!=0&&d*D<=0){D=d;n=1;A[0]=B=P}; if(n>0){r=g=($1-B)/n;if(n>C){r=($1-A[n%C])/C}}; A[n++%C]=P=$1; printf "%3d %+09.5f %+09.5f\n", p*$1, p*g, p*r}'
    sqweek · 2015-09-19 15:45:40 11
  • Better -and faster- using bash printf. Show Sample Output


    -2
    printf "%50s\n"|tr ' ' -
    rodolfoap · 2010-01-07 08:49:46 6

  • -2
    printf "%d\n" \0x64
    4Aiur · 2010-01-09 02:50:50 3

  • -2
    printf "%.50d" 0 | tr 0 -
    sata · 2010-03-25 12:52:45 3
  • ‹ First  < 6 7 8 9 > 

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands


Check These Out

Look for English words in /dev/urandom
* to get the English dictionary: wget http://www.mavi1.org/web_security/wordlists/webster-dictionary.txt

Make Kali Linux look less suspicious by making the desktop look more like a windows machine
To revert back to Kali's original desktop. Just redo the same command with no options .

HTTP GET request on wireshark remotly

edit hex mode in vim
return to normal mode from hex mode :%!xxd -r

Check if it's your binary birthday!
Print out your age in days in binary. Today's my binary birthday, I'm 2^14 days old :-) . This command does bash arithmatic $(( )) on two dates: Today: $(date +%s) Date of birth: $(date +%s -d YYYY-MM-DD) The dates are expressed as the number of seconds since the Unix epoch (Jan 1970), so we devide the difference by 86400 (seconds per day). . Finally we pipe "obase=2; DAYS-OLD" into bc to convert to binary. (obase == output base)

diff the same file in two directories.
This is useful when you're diffing two files of the same name in radically different directory trees. For example: Set $ path1='/some/long/convoluted/path/to/all/of/your/source/from/a/long/dead/machine' then $ path2='/local/version/of/same/file' then run the command. Much easier on the eyes when you're looking back across your command history, especially if you're doing the same diff over and over again.

Belgian banking "structured communication"
Derived from current time down to minutes.

List detailed information about a ZIP archive
list zipfile info in long Unix ``ls -l'' format.

draw line separator (using knoppix5 idea)

Convert CSV to JSON
Replace 'csv_file.csv' with your filename.


Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: