Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Jul 022014
 

Trap bash exit signal

Answer:

To trap your script before exit, you can use the trap in bash, e.g.

#!/bin/bash

set -eu

function bye {
  echo "Good bye"
}

trap bye EXIT
sleep 1000 
# Quit the script by pressing Ctrl+C
Jul 292013
 

How to sum a particular column of a CSV file with awk

Answer:

Assume you have a CSV file like the following (only contain number)

1,2,3
2,3,4
3,4,5
...

How do you sum the nth column of this file? It is easy with the use of awk

e.g. Assume you want to sum the 2nd column:

# awk -F "," '{ sum += $2 } END { print sum }' test.txt

Jul 252013
 

File content redirection without using cat

Answer:

It is not uncommon that people have abused the command `cat` for many purpose, e.g. file I/O redirection

cat data.txt | sed 's/foo/bar/s'

You can avoid the cat command by the following commands:

data.txt < sed 's/foo/bar/s'
sed 's/foo/bar/s' < data.txt

Both directions are okay.

In fact, when you better understand the usage of some commands, you might find out that redirection is completely not needed.

e.g.

sed 's/foo/bar/s' data.txt