How to remove sections from each line of files in the Linux system?

LinuxOperating SystemOpen Source

In this article, we will learn to remove sections from each line of files in the Linux/Unix operating system.

To remove selected parts of lines from each FILE, we use the cut command in the Linux system.

The cut command is used to remove and print the selected section of each FILE in the Linux operating system using a terminal. It is also used to cut the selected parts of a line by byte position, character, and field. It is also been ported to the IBM i operating system.

Syntax

The general syntax of the cut command is as follows

cut OPTION... [FILE]...

Brief description of options available in the cut command.

Sr.No.Option & Description
1-b, --bytes=LIST
Select only specifies bytes
2-c, --characters=LIST
Select only specifies characters
3-d, --delimiter=DELIM
Specify delimiter instead of TAB
4-f, --fields=LIST
Select only specified fields, and display any line that without delimiter, unless the -s option is specified
5-n
With option -b, do not split multibyte characters
6--complement
Complement the set of selected bytes, characters, or fields
7-z, --zero -terminated
Line delimiter is NULL, not newline
8--help
Display this help and exit
9--version
Output version information and exit

Example

To cut the specifies bytes from every column without range, we use -b or --byte option with the cut command in the Linux system.

Here, we will cut only two bytes from every column from a file as shown below.

vikash@tutorialspoint: ~/shadow$ cut -b 1,2 text1.txt
ar
ry
sa
st
to
ut
va
vikash@tutorialspoint− ~/shadow$

To cut the specified character from every column, we use -c or --characters option with the cut command in the Linux system.

Here, we will cut only the first, second, and fourth characters from every column from a file as shown below.

vikash@tutorialspoint − ~/shadow$ cut -c 1,2,4 text1.txt
ara
ryn
sa
stv
to
uta
vah
vikash@tutorialspoint − ~/shadow$

To cut the specified range character from each column, we need to specify range with -c option as shown below.

vikash@tutorialspoint −~/shadow$ cut -c 2-4 text1.txt
rya
yan
am
tev
om
tka
ash

In the above example, we cut the second to fourth characters from each column from a file in the Linux system.

To check more information about the cut command, we use the --help option with the cut command as shown below.

$ cut --help

To check version information of the cut command, we use the --version option with the cut command as shown below.

$ cut --version
raja
Published on 01-Jul-2021 15:29:33
Advertisements