Category Archives: bash

How to change default editor

Each works well with your favorite text editor. It is important that there is a default editor known. In debian and in other linux distro, default editor is vi.

You could change default editor:

  1. during distro installation
  2. custom each user into .bashrc or .profile file with line:
    export EDITOR=/usr/bin/emacs
  3. custom locally in a shell session and/or particular program:
    env EDITOR=nano crontab -e

How to add line number

Simple but useful. The sample file is “,” delimited.
$ cat sample
3232,32332,54545,34
3233,45645,23233,23
1211,1212,4343,434
3434,121121,121,33

If I have to add the line number as the first field. Then
$ awk '{$1=$1; print NR,$0}' sample
1|3232|32332|54545|34
2|3233|45645|23233|23
3|1211|1212|4343|434
4|3434|121121|121|33

If I have to change the field separator of the above file from “,” to “|” (can also be done using ‘tr’) and have to add the line number as the first field. Then
$ awk 'BEGIN{FS=",";OFS="|"} {$1=$1; print NR,$0}' sample
1|3232|32332|54545|34
2|3233|45645|23233|23
3|1211|1212|4343|434
4|3434|121121|121|33

How to replace text in single or multiple files

sed commands change from distribution to distribution. The proposed method should be working for each distribution.
for i in *.file; do sed -i _modified 's/foo/bar/g' "$i"; mv "$i"_modified "$i"; done

If you want add filename into file, you could join another sed command. Our files have code_BLABLA.foo format:
for i in *.foo; do m="$( echo $i | sed 's/_[A-Z_]*.foo//g' )"; sed -i _ 's/#/code='$m'/g' "$i"; done

If you need add also “-” into code because it has ABC12345 format and you want ABC-12345 format:
for i in *.foo; do j="$( echo $i | sed 's/_[A-Z_]*.foo//g' )"; k="$( echo $j | sed 's/\([A-Z]*\)/\1-/' )"; sed -i _ 's/#/code='$k'/g' "$i"; done