Increment aaa to aab using Bash? - bash

How can I increment characters similar to how numbers are done in bash?
Example; aaa -> zzz
for i in {aaa..zzz}; do
echo -n $i;
done
Should result in:
aaa aab aac (...) zzx zzy zzz

printf '%s ' {a..z}{a..z}{a..z}
If you really want to increment a character, you have to jump through some hoops:
First, you have to get the ordinal value of the character. This can be done with the shell's weird leading-quote syntax:
$ printf -v ordA '%d' '"A'
$ echo "$ordA"
65
Next, you need to add one to that:
$ ordB=$(( 1 + ordA ))
$ echo "$ordB"
66
Then you need to format that value so it can be printfed as a character:
$ printf -v fmtB '\\x%x' "$ordB"
$ echo "$fmtB"
\x42
Then, you finally printf it:
$ printf -v chrB "$fmtB"
$ echo "$chrB"
B
Whew. I'm sure some of that can be simplified, but those're the actual steps that need to be taken.

echo {a..z}{a..z}{a..z}
would suffice.

for n in {a..z}{a..z}{a..z}; do echo -n " $n"; done

Expanding on a comment to the answer by kojiro, if you really want to know how to increment an alphabetic string (as opposed to enumerating all possibilities), here's a solution (bash only, and it depends on the shell option extglob). It only works on strictly alphabetic lower-case strings, but it should be "obvious" how to extend it:
inc () {
local pfx=${1%%[^z]*(z)};
[[ $pfx != $1 ]] && echo $pfx$(tr a-z b-za <<<${1:${#pfx}})
}
Example:
$ a=zyy; while echo $a; a=$(inc $a); do :; done
zyy
zyz
zza
zzb
zzc
zzd
zze
zzf
zzg
zzh
zzi
zzj
zzk
zzl
zzm
zzn
zzo
zzp
zzq
zzr
zzs
zzt
zzu
zzv
zzw
zzx
zzy
zzz

Related

BASH text edit with seq

With this I can callmyscrip.sh 100 and this will print 100 rows with the content generated by seq, but what's the best way to separate the content TEXT="xxx yyy ${this}" for readability with a variable?
#!/bin/bash
howmanytimes=$1
for this in $(seq -w ${howmanytimes}); do echo " /
-- ${this}
"; done
this instead would not work as $this isn't replaced:
#!/bin/bash
howmanytimes=$1
TEXT="THIS WOULD NOT WORK: ${this}"
for this in $(seq -w ${howmanytimes}); do echo ${TEXT} ; done
export $TEXT
seq(1) is nonstandard, inefficient and useless.
Check http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Conditional_Loops
With ksh:
#!/bin/ksh
txt='this should work with int: '
for i in {0..$1}; do
echo "$txt $i"
done
With bash:
#!/bin/bash
txt='this should work with int: '
for ((i=0; i<=$1; i++)) {
echo "$txt $i"
}
You can wrap your dynamic text in a bash function:
#!/bin/bash
get_content() {
echo "THIS WOULD WORK: $1"
}
how_many_times=$1
for i in $(seq -w ${how_many_times}); do
echo "$(get_content $i)"
done
If you just need to output the content, can simplify it like this:
#!/bin/bash
get_content() {
echo "THIS WOULD WORK: $1"
}
how_many_times=$1
for i in $(seq -w ${how_many_times}); do
get_content $i
done
Check your script with shellcheck. printf is a simple template language. I could see:
#!/bin/bash
howmanytimes=$1
text="THIS WOULD WORK: %s"
for this in $(seq -w "${howmanytimes}"); do
printf "$text" "$this"
done
You could use envsubst to replace environment, however in this case printf looks way clearer. Research quoting in shell.
#!/bin/bash
howmanytimes=$1
text='THIS WOULD WORK: ${THIS}'
for this in $(seq -w "${howmanytimes}"); do
THIS="$this" envsubst <<<"$text"
done
You can use printf directly, and skip the loop entirely:
#!/bin/bash
howmanytimes=$1
text="This WILL work: %s"
printf "${text}\n" $(seq -w ${howmanytimes})
Note that \n needs to be added to the format string, since printf doesn't add a newline automatically like echo does. If you want additional newlines (like in the example), you can add them as either \n or actual newlines, in either the format variable or where it's used in the printf argument. Also, if you want to include a literal backslash or percent sign in the string, double it (i.e. %% to print %, or \\ to print \).
BTW, since printf is a bash builtin, it's not subject to the normal argument list length limits, so this'll work even with very large numbers of numbers.

how to remove leading zeros from negative numbers in shell

Is there any simple way to remove leading zeros from a negative number in shell?
For example : for a number like -02, the output will be -2
There a multiply ways to do this:
a="-02"
echo "$((a+0))"
Another with regex:
a="-02"
echo "${a//-0/-}"
Or
a="-02"
[[ "$a" =~ ^(-*|\+*)0*(.*)$ ]]
echo "${BASH_REMATCH[1]}${BASH_REMATCH[2]}"
And bc:
a="-02"
bc <<< "$a + 0"
What about using the builtin printf?
$ num=-02
$ printf "%d\n" "$num"
-2
One solution as I know is the following :
echo -02 | awk '{$0=int($0)}1'
but it only works with integer number. For floating is there any way?

How can I extract the last X folders from the path in k shell

Say I have a path name /server/user/folderA/folderB/folderC, how would I extract (to a variable) just the last few folders? I'm looking for something that will be flexible enough to give me folderC, or folderB/folderC, or folderA/folderB/folderC, etc.
I'm trying to use sed, but I'm not sure that's the best approach.
This would have to be in either ksh or csh (no bash on our machines, sadly)
This will get you started:
arr=( $(echo "/server/user/folderA/folderB/folderC" | sed 's#/# #g') )
echo ${#arr[*]}
echo ${arr[*]}
echo ${arr[3]}
echo "${arr[2]}/${arr[3]}/${arr[4]}"
output
5
server user folderA folderB folderC
folderB
folderA/folderB/folderC
IHTH
You can use arrays, but ksh88 (at least the one I tested with, on Solaris 8) uses the old Korn Shell syntax of set -A, and it doesn’t do (( i++ )) either, so this looks a bit more baroque than contemporary ksh93 or mksh code. On the other hand, I’m also giving you a function to extract the last n items ;)
p=/server/user/folderA/folderB/folderC
saveIFS=$IFS
IFS=/
set -A fullpath -- $p
echo all: "${fullpath[*]}"
unset fullpath[0] # leading slash
unset fullpath[1]
unset fullpath[2]
echo all but first two: "${fullpath[*]}"
IFS=$saveIFS
# example function to get the last n:
function pathlast {
typeset saveIFS parr i=0 n
saveIFS=$IFS
IFS=/
set -A parr -- $2
(( n = ${#parr[*]} - $1 ))
while (( i < n )); do
unset parr[i]
(( i += 1 ))
done
echo "${parr[*]}"
IFS=$saveIFS
}
for lst in 1 2 3; do
echo all but last $lst: $(pathlast $lst "$p")
done
Output:
tg#stinky:~ $ /bin/ksh x
all: /server/user/folderA/folderB/folderC
all but first two: folderA/folderB/folderC
all but last 1: folderC
all but last 2: folderB/folderC
all but last 3: folderA/folderB/folderC
Other than the first line setting $p, you can just copy the function part.
This could be done with perl if you've got it:
$ path=/server/user/folderA/folderB/folderC
$ X=3
$ echo $path|perl -F/ -ane '{print join "/",#F[(#F-'$X')..(#F-1)]}'
folderA/folderB/folderC

Bash variable substitution and strings

Let's say I have two variables:
a="AAA"
b="BBB"
I read a string from a file. This string is the following:
str='$a $b'
How to create a new string from the first one that substitutes the variables?
newstr="AAA BBB"
bash variable indirection whithout eval:
Well, as eval is evil, we may try to make this whithout them, by using indirection in variable names.
a="AAA"
b="BBB"
str='$a $b'
newstr=()
for cnt in $str ;do
[ "${cnt:0:1}" == '$' ] && cnt=${cnt:1} && cnt=${!cnt}
newstr+=($cnt)
done
newstr="${newstr[*]}"
echo $newstr
AAA BBB
Another try:
var1="Hello"
var2="2015"
str='$var1 world! Happy new year $var2'
newstr=()
for cnt in $str ;do
[ "${cnt:0:1}" == '$' ] && cnt=${cnt:1} && cnt=${!cnt}
newstr+=($cnt)
done
newstr="${newstr[*]}"
echo $newstr
Hello world! Happy new year 2015
Addendum As correctly pointed by #EtanReisner's comment, if your string do contain some * or other glob expendable stings, you may have to use set -f to prevent bad things:
cd /bin
var1="Hello"
var2="star"
var3="*"
str='$var1 this string contain a $var2 as $var3 *'
newstr=()
for cnt in $str ;do
[ "${cnt:0:1}" == '$' ] && cnt=${cnt:1} && cnt=${!cnt};
newstr+=("$cnt");
done;
newstr="${newstr[*]}"
echo "$newstr"
Hello this string contain a star as * bash bunzip2 busybox....zmore znew
echo ${#newstr}
1239
Note: I've added " at newstr+=("$cnt"); to prevent glob expansion, but set -f seem required...
newstr=()
set -f
for cnt in $str ;do
[ "${cnt:0:1}" == '$' ] && cnt=${cnt:1} && cnt=${!cnt}
newstr+=("$cnt")
done
set +f
newstr="${newstr[*]}"
echo "$newstr"
Hello this string contain a star as * *
Nota 2: This is far away from a perfect solution. For sample if string do contain ponctuation, this won't work again... Example:
str='$var1, this string contain a $var2 as $var3: *'
with same variables as previous run will render:
' this string contain a star as *' because ${!var1,} and ${!var3:} don't exist.
... and if $str do contain special chars:
As #godblessfq asked:
If str contains a line break, how do I do the substitution and preserve the newline in the output?
So this is not robust as every indirected variable must be first, last or space separated from all special chars!
str=$'$var1 world!\n... 2nd line...'
var1=Hello
newstr=()
set -f
IFS=' ' read -d$'\377' -ra array <<<"$str"
for cnt in "${array[#]}";do
[ "${cnt:0:1}" == '$' ] && cnt=${cnt:1} && cnt=${!cnt}
newstr+=("$cnt")
done
set +f
newstr="${newstr[*]}"
echo "$newstr"
Hello world!
... 2nd line...
As <<< inline string add a trailing newline, last echo command could be written:
echo "${newstr%$'\n'}"
The easiest solution is to use eval:
eval echo "$str"
To assign it to a variable, use command substitution:
replaced=$(eval echo "$str")
Disclaimer: I only discovered perl an hour ago. But this seems to work robustly, whatever special characters you throw at it:
newstr=$(a2="$a" b2="$b" perl -pe 's/\$a\b/$ENV{a2}/g; s/\$b\b/$ENV{b2}/g' <(echo -e "$str"))
Test:
a='A*A\nA'
b='B*B\nB'
str='$a $aa * \n $b $bb'
newstr=$(a2="$a" b2="$b" perl -pe 's/\$a\b/$ENV{a2}/g; s/\$b\b/$ENV{b2}/g' <(echo -e "$str"))
echo -e "$newstr"
Output:
A*A
A $aa *
B*B
B $bb
I'd use awk solution with awk-variables. This will allow passing a text containing special chars and subsitute any placeholder with it.
a workaround to recognize $ would be using [\x24]:
awk -v a="$a" -v b="$b" '{gsub("[\x24]a",a);gsub("[\x24]b",b); print}' <<< $str
here
-v defines variable a="$a"
[x24] is ASCII for $, so [x24]a equal to $a
gsub(x,y) - replaces x with y

Padding characters in printf

I am writing a bash shell script to display if a process is running or not.
So far, I got this:
printf "%-50s %s\n" $PROC_NAME [UP]
The code gives me this output:
JBoss [DOWN]
GlassFish [UP]
verylongprocessname [UP]
I want to pad the gap between the two fields with a '-' or '*' to make it more readable. How do I do that without disturbing the alignment of the fields?
The output I want is:
JBoss ------------------------------------------- [DOWN]
GlassFish --------------------------------------- [UP]
verylongprocessname ----------------------------- [UP]
Pure Bash, no external utilities
This demonstration does full justification, but you can just omit subtracting the length of the second string if you want ragged-right lines.
pad=$(printf '%0.1s' "-"{1..60})
padlength=40
string2='bbbbbbb'
for string1 in a aa aaaa aaaaaaaa
do
printf '%s' "$string1"
printf '%*.*s' 0 $((padlength - ${#string1} - ${#string2} )) "$pad"
printf '%s\n' "$string2"
string2=${string2:1}
done
Unfortunately, with that technique, the length of the pad string has to be hardcoded to be longer than the longest one you think you'll need, but the padlength can be a variable as shown. However, you can replace the first line with these three to be able to use a variable for the length of the pad:
padlimit=60
pad=$(printf '%*s' "$padlimit")
pad=${pad// /-}
So the pad (padlimit and padlength) could be based on terminal width ($COLUMNS) or computed from the length of the longest data string.
Output:
a--------------------------------bbbbbbb
aa--------------------------------bbbbbb
aaaa-------------------------------bbbbb
aaaaaaaa----------------------------bbbb
Without subtracting the length of the second string:
a---------------------------------------bbbbbbb
aa--------------------------------------bbbbbb
aaaa------------------------------------bbbbb
aaaaaaaa--------------------------------bbbb
The first line could instead be the equivalent (similar to sprintf):
printf -v pad '%0.1s' "-"{1..60}
Or similarly for the more dynamic technique:
printf -v pad '%*s' "$padlimit"
Or this (which allows multi-character "ellipses" without having to modify the format string to accommodate the number of characters - .1 in the example above). It assumes that variables with names such as $_1, $_2, etc., are unset or empty.:
printf -v pad '%s' "<>"$_{1..60}
You can do the printing all on one line if you prefer:
printf '%s%*.*s%s\n' "$string1" 0 $((padlength - ${#string1} - ${#string2} )) "$pad" "$string2"
Pure Bash. Use the length of the value of 'PROC_NAME' as offset for the fixed string 'line':
line='----------------------------------------'
PROC_NAME='abc'
printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}"
PROC_NAME='abcdef'
printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}"
This gives
abc ------------------------------------- [UP]
abcdef ---------------------------------- [UP]
Trivial (but working) solution:
echo -e "---------------------------- [UP]\r$PROC_NAME "
I think this is the simplest solution. Pure shell builtins, no inline math. It borrows from previous answers.
Just substrings and the ${#...} meta-variable.
A="[>---------------------<]";
# Strip excess padding from the right
#
B="A very long header"; echo "${A:0:-${#B}} $B"
B="shrt hdr" ; echo "${A:0:-${#B}} $B"
Produces
[>----- A very long header
[>--------------- shrt hdr
# Strip excess padding from the left
#
B="A very long header"; echo "${A:${#B}} $B"
B="shrt hdr" ; echo "${A:${#B}} $B"
Produces
-----<] A very long header
---------------<] shrt hdr
Simple but it does work:
printf "%-50s%s\n" "$PROC_NAME~" "~[$STATUS]" | tr ' ~' '- '
Example of usage:
while read PROC_NAME STATUS; do
printf "%-50s%s\n" "$PROC_NAME~" "~[$STATUS]" | tr ' ~' '- '
done << EOT
JBoss DOWN
GlassFish UP
VeryLongProcessName UP
EOT
Output to stdout:
JBoss -------------------------------------------- [DOWN]
GlassFish ---------------------------------------- [UP]
VeryLongProcessName ------------------------------ [UP]
There's no way to pad with anything but spaces using printf. You can use sed:
printf "%-50s#%s\n" $PROC_NAME [UP] | sed -e 's/ /-/g' -e 's/#/ /' -e 's/-/ /'
echo -n "$PROC_NAME $(printf '\055%.0s' {1..40})" | head -c 40 ; echo -n " [UP]"
Explanation:
printf '\055%.0s' {1..40} - Create 40 dashes
(dash is interpreted as option so use escaped ascii code instead)
"$PROC_NAME ..." - Concatenate $PROC_NAME and dashes
| head -c 40 - Trim string to first 40 chars
This one is even simpler and execs no external commands.
$ PROC_NAME="JBoss"
$ PROC_STATUS="UP"
$ printf "%-.20s [%s]\n" "${PROC_NAME}................................" "$PROC_STATUS"
JBoss............... [UP]
using echo only
The anwser of #Dennis Williamson is working just fine except I was trying to do this using echo. Echo allows to output charcacters with a certain color. Using printf would remove that coloring and print unreadable characters. Here's the echo-only alternative:
string1=abc
string2=123456
echo -en "$string1 "
for ((i=0; i< (25 - ${#string1}); i++)){ echo -n "-"; }
echo -e " $string2"
output:
abc ---------------------- 123456
of course you can use all the variations proposed by #Dennis Williamson whether you want the right part to be left- or right-aligned (replacing 25 - ${#string1} by 25 - ${#string1} - ${#string2} etc...
Here's another one:
$ { echo JBoss DOWN; echo GlassFish UP; } | while read PROC STATUS; do echo -n "$PROC "; printf "%$((48-${#PROC}))s " | tr ' ' -; echo " [$STATUS]"; done
JBoss -------------------------------------------- [DOWN]
GlassFish ---------------------------------------- [UP]
If you are ending the pad characters at some fixed column number, then you can overpad and cut to length:
# Previously defined:
# PROC_NAME
# PROC_STATUS
PAD="--------------------------------------------------"
LINE=$(printf "%s %s" "$PROC_NAME" "$PAD" | cut -c 1-${#PAD})
printf "%s %s\n" "$LINE" "$PROC_STATUS"
Simple Console Span/Fill/Pad/Padding with automatic scaling/resizing Method and Example.
function create-console-spanner() {
# 1: left-side-text, 2: right-side-text
local spanner="";
eval printf -v spanner \'"%0.1s"\' "-"{1..$[$(tput cols)- 2 - ${#1} - ${#2}]}
printf "%s %s %s" "$1" "$spanner" "$2";
}
Example: create-console-spanner "loading graphics module" "[success]"
Now here is a full-featured-color-character-terminal-suite that does everything in regards to printing a color and style formatted string with a spanner.
# Author: Triston J. Taylor <pc.wiz.tt#gmail.com>
# Date: Friday, October 19th, 2018
# License: OPEN-SOURCE/ANY (NO-PRODUCT-LIABILITY OR WARRANTIES)
# Title: paint.sh
# Description: color character terminal driver/controller/suite
declare -A PAINT=([none]=`tput sgr0` [bold]=`tput bold` [black]=`tput setaf 0` [red]=`tput setaf 1` [green]=`tput setaf 2` [yellow]=`tput setaf 3` [blue]=`tput setaf 4` [magenta]=`tput setaf 5` [cyan]=`tput setaf 6` [white]=`tput setaf 7`);
declare -i PAINT_ACTIVE=1;
function paint-replace() {
local contents=$(cat)
echo "${contents//$1/$2}"
}
source <(cat <<EOF
function paint-activate() {
echo "\$#" | $(for k in ${!PAINT[#]}; do echo -n paint-replace \"\&$k\;\" \"\${PAINT[$k]}\" \|; done) cat;
}
EOF
)
source <(cat <<EOF
function paint-deactivate(){
echo "\$#" | $(for k in ${!PAINT[#]}; do echo -n paint-replace \"\&$k\;\" \"\" \|; done) cat;
}
EOF
)
function paint-get-spanner() {
(( $# == 0 )) && set -- - 0;
declare -i l=$(( `tput cols` - ${2}))
eval printf \'"%0.1s"\' "${1:0:1}"{1..$l}
}
function paint-span() {
local left_format=$1 right_format=$3
local left_length=$(paint-format -l "$left_format") right_length=$(paint-format -l "$right_format")
paint-format "$left_format";
paint-get-spanner "$2" $(( left_length + right_length));
paint-format "$right_format";
}
function paint-format() {
local VAR="" OPTIONS='';
local -i MODE=0 PRINT_FILE=0 PRINT_VAR=1 PRINT_SIZE=2;
while [[ "${1:0:2}" =~ ^-[vl]$ ]]; do
if [[ "$1" == "-v" ]]; then OPTIONS=" -v $2"; MODE=$PRINT_VAR; shift 2; continue; fi;
if [[ "$1" == "-l" ]]; then OPTIONS=" -v VAR"; MODE=$PRINT_SIZE; shift 1; continue; fi;
done;
OPTIONS+=" --"
local format="$1"; shift;
if (( MODE != PRINT_SIZE && PAINT_ACTIVE )); then
format=$(paint-activate "$format&none;")
else
format=$(paint-deactivate "$format")
fi
printf $OPTIONS "${format}" "$#";
(( MODE == PRINT_SIZE )) && printf "%i\n" "${#VAR}" || true;
}
function paint-show-pallette() {
local -i PAINT_ACTIVE=1
paint-format "Normal: &red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
paint-format " Bold: &bold;&red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
}
To print a color, that's simple enough: paint-format "&red;This is %s\n" red
And you might want to get bold later on: paint-format "&bold;%s!\n" WOW
The -l option to the paint-format function measures the text so you can do console font metrics operations.
The -v option to the paint-format function works the same as printf but cannot be supplied with -l
Now for the spanning!
paint-span "hello " . " &blue;world" [note: we didn't add newline terminal sequence, but the text fills the terminal, so the next line only appears to be a newline terminal sequence]
and the output of that is:
hello ............................. world
Bash + seq to allow parameter expansion
Similar to #Dennis Williamson answer, but if seq is available, the length of the pad string need not be hardcoded. The following code allows for passing a variable to the script as a positional parameter:
COLUMNS="${COLUMNS:=80}"
padlength="${1:-$COLUMNS}"
pad=$(printf '\x2D%.0s' $(seq "$padlength") )
string2='bbbbbbb'
for string1 in a aa aaaa aaaaaaaa
do
printf '%s' "$string1"
printf '%*.*s' 0 $(("$padlength" - "${#string1}" - "${#string2}" )) "$pad"
printf '%s\n' "$string2"
string2=${string2:1}
done
The ASCII code "2D" is used instead of the character "-" to avoid the shell interpreting it as a command flag. Another option is "3D" to use "=".
In absence of any padlength passed as an argument, the code above defaults to the 80 character standard terminal width.
To take advantage of the the bash shell variable COLUMNS (i.e., the width of the current terminal), the environment variable would need to be available to the script. One way is to source all the environment variables by executing the script preceded by . ("dot" command), like this:
. /path/to/script
or (better) explicitly pass the COLUMNS variable when executing, like this:
/path/to/script $COLUMNS

Resources