0
0
Bash Scriptingscripting~5 mins

cut and paste in Bash Scripting

Choose your learning style9 modes available
Introduction
Cut and paste help you extract or combine parts of text quickly in scripts or the command line.
You want to get specific columns from a text file or command output.
You need to join fields from two files side by side.
You want to rearrange or remove parts of lines in a file.
You want to copy some text from one place and add it to another.
You want to process data in scripts by cutting or pasting fields.
Syntax
Bash Scripting
cut [options] [file]
paste [options] [file1 file2 ...]
Use 'cut' to extract sections from each line of a file or input.
Use 'paste' to merge lines of files horizontally, separated by tabs by default.
Examples
Extracts the second field from a CSV file using comma as delimiter.
Bash Scripting
cut -d',' -f2 file.csv
Joins lines from file1.txt and file2.txt side by side separated by tabs.
Bash Scripting
paste file1.txt file2.txt
Cuts the first 5 characters from each line of file.txt.
Bash Scripting
cut -c1-5 file.txt
Joins lines from two files using ':' as the delimiter instead of tab.
Bash Scripting
paste -d ':' file1.txt file2.txt
Sample Program
This script creates two files, extracts the color column from the CSV, then pastes the names and fruit info side by side with ':' separator.
Bash Scripting
# Create two sample files
printf "apple,red,1\nbanana,yellow,2\ncherry,red,3\n" > fruits.csv
printf "John\nJane\nJoe\n" > names.txt

# Extract second field (color) from fruits.csv
cut -d',' -f2 fruits.csv

# Paste names.txt and fruits.csv side by side with ':' delimiter
paste -d ':' names.txt fruits.csv

# Clean up
rm fruits.csv names.txt
OutputSuccess
Important Notes
If you do not specify a delimiter with cut, it defaults to tab.
Paste joins lines horizontally; if files have different line counts, missing lines appear empty.
Use quotes around delimiters if they are special characters.
Summary
Cut extracts parts of lines by fields or characters.
Paste joins lines from multiple files side by side.
Both are useful for quick text processing in scripts.