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 237
  • 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 343

  • 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

tar via network

iso-8859-1 to utf-8 safe recursive rename
This command is a powerful "detoxifier" that eliminates special chars, spaces and all those little chars we don't like. It support several "sequences" so be sure to check your /usr/local/etc/detoxrc while at it... and maybe define your own

complete extraction of a debian-package
extracts the debian-package $debfile to $extractdir, including all packaging-information. to repack the package, just type: $dpkg-deb -b $extractdir

Adjust gamma so monitor doesn't mess up your body's clock
[UPDATE: Now works for multiple connected outputs] I woke up around midnight with an urge to do some late night hacking, but I didn't want a bright monitor screwing up my body's circadian rhythm. I've heard that at night blue (short wavelength) lights are particularly bad for your diurnal clock. That may be a bunch of hooey, but it is true that redder (longer wavelength) colors are easier on my eyes at night. This command makes the screen dimmer and adjusts the gamma curves to improve contrast, particularly darkening blues and greens (Rɣ=2, Gɣ=3, Bɣ=4). To reset your screen to normal, you can run this command: $ xrandr | sed -n 's/ connected.*//p' | xargs -n1 -tri xrandr --output {} --brightness 1 --gamma 1:1:1 or, more briefly, $ xgamma -g 1 Note: The sed part is fragile and wrong. I'm doing it this way because of a misfeature in xrandr(1), which requires an output be specified but has no programmatic way of querying available outputs. Someone needs to patch up xrandr to be shell script friendly or at least add virtual outputs named "PRIMARY" and "ALL". . Todo: Screen should dim (gradually) at sunset and brighten at sunrise. I think this could be done with a self-resubmitting at job, but I'm running into the commandlinefu 127 character limit just getting the sunrise time: $ wget http://aa.usno.navy.mil/cgi-bin/aa_pap.pl --post-data=$(date "+xxy=%Y&xxm=%m&xxd=%d")"&st=WA&place=Seattle" -q -O- | sed -rn 's/\W*Sunrise\W*(.*)/\1/p' I hope some clever hacker comes up with a command line interface to Google's "OneBox", since the correct time shows up as the first hit when googling for "sunrise:cityname". . [Thank you to @flatcap for the sed improvement, which is much better than the head|tail|cut silliness I had before. And thank you to @braunmagrin for pointing out that the "connected" output may not be on the second line.]

Filter out all blank or commented (starting with #) lines

list files recursively by size

remove all spaces from all files in current folder

Which processes are listening on a specific port (e.g. port 80)
swap out "80" for your port of interest. Can use port number or named ports e.g. "http"

prints line numbers
the sed way to print line numbers

Size (in bytes) of all RPM packages installed
This command will output the size of all RPM packages and string them together into one enormous addition command which will be calculated by the echo $(( ))


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: