bash commands - ghdrako/doc_snipets GitHub Wiki

fold

cat longfile2.txt |fold -45 # “fold” the contents of longfile2.txt into lines whose length is 45 # zawija tekts w linie o dl 45 znakow

declare

declare -i var=10 # set an integer variable
declare -a arr=(1 2 3) # create an array variable

readonly

readonly is a Bash keyword used to create variables that cannot be changed or unset later.

readonly var="hello" # set a read-only variable

env

printenv

which whereis

printf

  • Format specifiers
  • Width specifiers
printf "%-5s %-10s %-4s\n" ABC DEF GHI
printf "%-5s %-10s %-4.2f\n" ABC DEF 12.3456

-v var option, assigns the output into a variable rather than displaying it, similar to sprintf in C.

### Set a $today variable using -v
$ printf -v today '%(%F)T' '-1'
$ echo $today
2021-08-13

%q quote the argument in a way that can be reused as shell input

$ printf '%q' "This example is from $today\n"
This\ example\ is\ from\ 2021-08-13\\n

This can be useful for reusing output elsewhere, creating formatted output and debugging where you need to be able to see hidden or control characters or fields.

cut - extract fields with a specified delimiter as well as a range of columns from an input stream

$ x="abc def ghi"
$ echo $x | cut -d" " -f2 # using space " " as IFS, and -f2 to indicate the secondcolumn
def
$ x="abc def ghi"
$ echo $x | cut -c2-5
bc d
$ fileName="06.22.04p.vp.0.tgz"
$ f1=`echo $fileName | cut -d"." -f1`
$ f2=`echo $fileName | cut -d"." -f2`
$f3=`echo $fileName | cut -d"." -f3`
$ f4=`echo $fileName | cut -d"." -f4`
$ f5=`echo $fileName | cut -d"." -f5`
$ f5=`expr $f5 + 12`
$ newFileName="${f1}.${f2}.${f3}.${f4}.${f5}"
$ echo "newFileName: $newFileName"
newFileName: 06.22.04p.vp.12

paste - combine two files in a “pairwise” fashion

$ cat list1
cp abc.sh
cp abc2.sh
cp abc3.sh

$ cat list2
def.sh
def2.sh
def3.sh

$ paste list1 list2 >list1.sh

$ cat list1.sh
cp abc.sh def.sh
cp abc2.sh def2.sh
cp abc3.sh def3.sh 

$ chmod +x list1.sh
$ ./list1.sh

Reverse column order

$ cat namepairs.csv
Jane,Smith
Dave,Jones
Sara,Edwards


$ inputfile="namepairs.csv"
$ outputfile="reversenames.csv"
$ fnames="fnames"
$ lnames="lnames"
$ cat $inputfile|cut -d"," -f1 > $fnames
$ cat $inputfile|cut -d"," -f2 > $lnames
$ paste -d"," $lnames $fnames > $outputfile

$ cat $outputfile
Smith,Jane
Jones,Dave
Edwards,Sara

Simples solution using awk:

cat namepairs.txt |awk -F"," '{print $2 "," $1}'