Sed Command Examples

Insert a newline in front of pattern

Example your text in the file is as below

Updated number of BobUpdated number of ChrisUpdated number of Peter

If you want format the text as below
Updated number of Bob
Updated number of Chris
Updated number of Peter


Need to use the command as below.

 [root@server ~]# sed 's/Update/\n&/g'  test.txt

Sum of the Values of Column Using AWK.

For example, I have a file called apples.txt with the following content and I want to total them up.

Apples in Box 1 = 100
Apples in Box 2 = 564
Apples in Box 3 = 214
Apples in Box 4 = 124
Apples in Box 5 = 785
Apples in Box 6 = 398
Apples in Box 7 = 125
Apples in Box 8 = 753
Apples in Box 9 = 357
Apples in Box 10 = 951

So just cat the file and use AWK command awk ‘{SUM+=$6}END{print SUM}’ to total them up

make sure to use the right column in awk command, like in our example I want to SUM the column 6 so I used ‘{SUM+=$6}

[root@server ~]# cat  example.txt | awk '{SUM+=$6}END{print SUM}'
4371

Eval Command in Linux

Eval is built in unix command – it’s used to execute arguments as shell commands. It’s useful when you have command stored in variable and you want to execute it.

[root@server Files]# mycommand="ls -ltr"

[root@server Files]# echo $mycommand
ls -ltr

[root@server Files]# eval $mycommand
total 0
-rw-r--r-- 1 root root 0 Nov  5 07:40 file1.txt
-rw-r--r-- 1 root root 0 Nov  5 07:40 file3.txt
-rw-r--r-- 1 root root 0 Nov  5 07:40 file2.txt
[root@server Files]#

Look at the example above, I have stored the command ls – ltr in the variable mycommand so when I do echo it’s just prints what in the variable. But when I do eval followed with the variable – it will actually execute the command.

Eval is powerful command but it’s Evil – it has security issues as well.
You can find the details here

Avoid Confirmation while Copying Files

While copying files, using cp command you would have noticed that it always asks for the confirmation overwriting files like below.

[root@server ~]# cp -v test.txt example.txt
cp: overwrite ‘example.txt’?

Will see how you can avoid that – but before that let’s see why it happens.

This happens because of alias set in the .bashrc file.

[root@server ~]# cat .bashrc
# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

you can remove alias in .bashrc file – and you won’t be asked for confirmation ever again.

but if you want to skip confirmation for time being then you can call the cp command directly from bin – Example.

[root@server ~]# /bin/cp -v test.txt example.txt
‘test.txt’ -> ‘example.txt’
[root@server ~]#