Categorybash

bash variables magic

bashlove

I often find myself searching for a, say, left() or mid() function when coding bash. Somehow my subconscious mind seems to know I’m doing too much in bash and therefore tends to forget things like a simple left() in bash. So I note them here. Lets hope I don’t forget where I wrote that down…

len() in bash

$ var='Hello, World!'
$ echo "${#var}"
13

left() in bash

$ var='Hello, World!'
#${string:position:length}
$ echo "${var:0:5}"
Hello

right() in bash

$ var='Hello, World!'
#${string:position:length}
$ echo "${var:7:${#var}}"
World!
#or a litte more dynamic.. (the 6 most right chars)
echo "${var:$((${#var}-6)):${#var}}"
World!

mid() in bash

$ var='Hello, World!'
#${string:position:length}
$ echo "${var:4:4}"
o, W

string replace first in bash (substitute)

$ var='Hello, World!'
#${string/substring/replacement}
$ echo "${var/o/a}"
Hella, World!

string replace all in bash (substitute)

$ var='Hello, World!'
#${string//substring/replacement}
$ echo "${var//o/a}"
Hella, Warld!

Did I miss one?

Substitute patterns in a text file with Perl

Quickly substitute patterns in a text file with Perl:

$ echo "Hallo, Welt." > substitute
$ perl -pi -e 's/Ha/He/g;s/elt/orld/g' substitute
$ cat substitute
Hello, World.

I used it to convert some text files from dos to unix newline:

perl -pi -e 's/\r\n/\n/g' 

Tends to be very useful when scripting. If needed, you can batch substitute in combination with find:

find . -type f -exec perl -pi -e 's/A/B/g' {} \;

simple way to set time and date in bash

because I always forget:

date mmddhhMM

for examle:

sys:~# date
Sun Feb 19 06:01:32 CET 2012
sys:~# date 08271451
Mon Aug 27 14:51:00 CEST 2012
sys:~# date
Mon Aug 27 14:51:04 CEST 2012

replace newline with sed

update: I recommend this solution now.

Several times needed and always forgotten how it works: Replace newline on the shell with sed. So I decided to write it down here, that at least I know where to look for…

Example, convert this:

item1
item2
item3

into this:

item1;item2;item3

cat the file and pipe it through sed like so:

cat newlinefile | sed -n '1h;2,$H;${g;s/\n/;/g;p}'

happy substituting!

© 2017 netmess

Theme by Anders NorenUp ↑