String Manipulations in Bash

Length

$ VAR=Batur
$ echo ${#VAR}

Substrings

$ VAR=Batur
$ echo ${VAR:1}
$ echo ${VAR:2}
$ echo ${VAR:1:3}

Substring Match

${string##sub}
$ VAR="Batur Orkun"
$ echo ${VAR##Batur}
${string%%sub}
$ VAR="Batur Orkun"
$ echo ${VAR%%Orkun}
${string/pattern/replacement}
$ VAR="Batur Orkun"
$ echo ${VAR/r/R}
${string//pattern/replacement}
$ VAR="Batur Orkun"
$ echo ${VAR/r/R}
digit="456"if [[ $digit =~ [0-9] ]]; then
echo "$digit is a digit"
else
echo "digit is NO digit "
fi
digit="456a"if [[ $digit =~ ^-?[0-9]+$ ]]; then
echo "$digit is a digit"
else
echo "digit is NO digit "
fi

grep = global regular expression print

$ grep "batur" myfile
$ grep -n "batur" myfile
$ grep -l "batur" myfile
$ grep -i "batur" myfile
$ grep "Orkun$" myfile
$ grep "^Batur Orkun$" myfile
$ pgrep nginx

sed: stream editor

$ sed 's/devops/DevOps/' myfile
$ sed "s/devops/DevOps/" myfile > newfile
$ sed -ni "s/devops/DevOps/" myfile

“s” : substitute

Syntax: "s/regexp/replacement/flags"

“p”: Print

Syntax: "/pattern/ command"
$ ls -l | sed -n '/picus/ p'
$ ls -l | sed -n '/picus/ p' | grep '^d'
$ sed -i '/picus/ d' myfile

“d”: Delete command

AWK

BEGIN { …. initialization awk commands …}
{ …. man awk commands …}
END { …. finalization awk commands …}
$ ls -l | awk 'BEGIN {sum=0} {sum=sum+$5} END {print sum}'
$ echo "A-B-C-D-E" | awk -F "-" '{ print $2 }'
$ echo "A-B-C-D-E" | awk -F "-" '{ print $1,$5 }'
1) Name        Surname   City 
2) Batur Orkun Ankara 70
3) HaticeEbru Orkun Istanbul 95
$ awk '{print $2 “=” $4}' myfile
$ awk '/Orkun/ {print $0}' myfile
$ awk '/Orkun/{++cnt} END {print “Count = “, cnt}' myfile
$ awk 'length($2) > 5' myfile
$awk '{if ($5>70) print}' myfile
$ awk '{ print substr( $1, 0,1 ) }' myfile
$ awk '{if(NR>1)print}' myfile
$ awk '{if (NF==4) print}' myfile

--

--

--

DevOps & Software & Architect & Linux Geek — http://baturorkun.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Launch your (Software Development) Tech Career

DialogFlow: A Simple Way to Build your Voicebots and Chatbots

Phoenix: Setting up ENV Variables

Declarative Vs Imperative Programming

RazorPay — Android Integration

The story of how Ansible automated Amelco

Docker: An Introduction

Containerizing FrontEnd Application

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Batur Orkun

Batur Orkun

DevOps & Software & Architect & Linux Geek — http://baturorkun.com

More from Medium

Why Linux for Programmers?

Linux Loops and Functions

FOSS and learning Linux CLI: An early experience and just how it all started!

Piping on Linux 101