Linux/Unix  Command

How to remove the headers from a file using command in Linux?

# sed '1 d' file.txt

Outputs the file on standard output without the first line. In order to save the output to file, we need to use redirect operator which will redirects the output to a file.

# sed '1 d' file.txt > new_file.txt

How will you check the length of a line from a text file?

A ‘sed –n ‘n p’ file.txt‘, where ‘n‘ represents the line number and ‘p‘ print out the pattern space (to the standard 

sed –n 'n p' file.txt | wc –c

You are a Team-Leader of a group of staffs working for a company xyz. The company ask you to create a directory ‘dir_xyz’, such that any member of the group can create a file or access a file under it, but no one can delete the file, except the one created it. what will you do?

# mkdir dir_xyz # chmod g+wx dir_xyz # chmod +t dir_xyz

What is the use of cut command in Linux?

# cut -c1-10 txt_tecmint

To extract 2nd, 5th and 7th column of the same text file.

# cut -d;-f2 -f5 -f7 txt_tecmint

Viewing a range of lines of a document 

The following sed one-liner will return lines 5 through 10 from myfile.txt:

sed -n '5,10p' myfile.txt

Viewing the entire file except a given range 

To exclude lines 20through 35 from myfile.txt, do:

sed '20,35d' myfile.txt

Viewing non-consecutive lines and ranges 

Let’s display lines 5-7 and 10-13 from myfile.txt:

# sed -n -e '5,7p' -e '10,13p' myfile.txt

Replacing words or characters (basic substitution)

To replace every instance of the word version with story in myfile.txt, do:

# sed 's/version/story/g' myfile.txt

Additionally, you may want to consider using gi instead of g in order to ignore character case  # sed 's/version/story/gi' myfile.txt

To replace multiple blank spaces with a single space, we will use the output of ip route show and a pipeline:

# ip route show | sed 's/  */ /g'

Replacing words or characters inside a range

replacing words only within a line range (30 through 40, for example), you can do:

# sed '30,40 s/version/story/g' myfile.txt

Using regular expressions (advanced substitution) – I

Sometimes configuration files are loaded with comments. While this is certainly useful, it may be helpful to display only the configuration directives sometimes if you want to view them all at a glance.

To remove empty lines or those beginning with # from the Apache configuration file, do:

(^#) indicates the beginning of a line

^$ represents blank lines

In this particular case, the Apache configuration file has lines with #’s not at the beginning of some lines, so *# is used to remove those as well.

# sed '/^#\|^$\| *#/d' httpd.conf

Viewing lines containing with a given pattern

we may be interested in viewing the authorization and authentication activities that took place on July 2, as per the /var/log/secure log in a CentOS 7 server.

sed -n '/^Jul  1/ p' /var/log/secure

sasas

sasa

sasas

sas