Cut a section of text based on characters.
Useful when handling large file processing tasks.
echo "cutting text from input" | cut -c 1
The above command cuts the first character from the standard input and displays it in the terminal.
In this case, it is “c“.
echo "cutting text from input" | cut -c 1,3
This command will cut only the first and third characters of the input string and show them.
Remember not to exceed the character limit of your string.
echo "cutting text from input" | cut -c 1-12
Cuts characters from the first position to the twelfth position.
The result will be “cutting text“.
cut -c 1 test.txt
Displays only the first characters of each of the five rows of our file test.txt.
It is equivalent to the command
cat test.txt | cut -c 1
and provides the same result as we would get when using the byte flag.
cut -c 7,10 test.txt
Cuts only the seventh and tenth characters of each five rows.
You can specify any character positions as long as they fall within the range of available characters.
cut -c 1-12 test.txt
Outputs the first one to twelfth characters of each line in the test.txt file.
The cut command in Unix behaves the same when cutting a range of characters and range of bytes.
echo "cutting text from input" | cut -c 5-
The above cut command will cut the text starting from the fifth byte to the end of the string.
It can be beneficial when you need to cut from a specified character position until the end of the input stream.
Simply change the value after b while keeping the trailing – on.
cut -c 5- test.txt
This command will start cutting each of the five rows of the test.txt file from their fifth character position and will finish after reaching the end of every line.
The trailing hyphen(-) is mandatory for this kind of operation.
echo "cutting text from input" | cut -c -5
This command will only cut the first five character positions of our input.
Remember to add the preceding hyphen(-) else the output will not be the same as you expect.
cut -c -5 test.txt
This cut command in Unix will cut the first five characters of each line from the file test.txt.
Notice how the hyphen(-) is being used for the commands 21-24 in this list.
cut -c 1-5 test.txt | sort
Cuts the first five bytes of each row alphabetically.
The sort command doesn’t require any options when sorting alphabetically.
cut -c 1-5 test.txt | sort -r
Cuts the first five characters from each row and will show them after sorting in reverse.
cut -c 3 abcdef
returns:
c
A range must be provided in each case which consists of one of N, N-M, N-(N to last) or -M (first to M)
cut -c 2-4 abcdef
Press CTRL+D to stop inputting
returns:
bcd
cut -c 2,4,7 alongtext
returns:
lne
cut -c -2 abcdef
returns:
ab
cut -c 2- abcdef
returns:
bcdef
cut -c 1,6-9,16- alongtextwithnospaces
returns:
atextspaces