copied to clipboard!
string grep

Mastering grep and xargs: A Comprehensive Guide

updated: 2026/07/29 created: 2026/07/29

Introduction

grep and xargs are representative commands in Linux and Unix environments that streamline file searching and batch processing.

They are useful on their own, but when combined, you can pass search results directly to another command, enabling editing, deletion, and log investigation across multiple files with short commands.

This article explains everything from the basics to advanced usage in detail.

Reference: GNU grep

Basic Syntax of grep and xargs

Create File

cat << 'EOF' > input.txt apple banana orange apple grape banana EOF

Command

grep "banana" input.txt | xargs -I {} echo "Found: {}"

Result

Found: banana
Found: banana

Command

grep -v "apple" input.txt | xargs

Result

banana orange grape banana

How It Works

Command Role Description
grep "apple" input.txt Search Extracts lines containing "apple" from input.txt
grep "banana" input.txt | xargs -I {} echo "Found: {}" Search + argument expansion xargs receives grep's output line by line and executes it as an argument to echo
grep -v "apple" input.txt | xargs Exclusion search + argument combination Extracts lines not containing "apple", and xargs combines them into a single line of space-separated arguments for output

Explanation

grep is a command that searches text for lines matching a given condition.
By combining it with xargs, you can pass the search results as arguments to another command, enabling efficient batch processing.

How grep and xargs Pass Standard Input

Create File

cat << 'EOF' > input.txt apple banana grape apple juice orange EOF

Command

grep "apple" input.txt | xargs -I {} echo "found: {}"

Result

found: apple
found: apple juice

Command

grep "apple" input.txt | xargs

Result

apple apple juice

How It Works

Command Role Standard Input Standard Output
grep "apple" input.txt Searches for lines containing "apple" input.txt apple, apple juice
| Passes the previous command's standard output to the next grep's output Passed to xargs
xargs -I {} echo "found: {}" Expands standard input line by line into {} and executes the command grep's output Displays the processed string
xargs Converts standard input into space-separated arguments grep's output apple apple juice

Explanation

grep outputs its search results to standard output, and the pipe (|) passes that content to xargs as standard input.
xargs converts the received data into command-line arguments and passes them to the following command, allowing multi-line data to be processed efficiently.

Batch Processing Matched Files with grep and xargs

Create File

cat << 'EOF' > input.txt apple banana apple pie orange pineapple EOF

Command

grep -l "apple" *.txt | xargs -I {} wc -l {}

Result

5 input.txt

Command

grep -l "apple" *.txt | xargs -I {} cp {} {}.bak

Result

no output

Command

ls *.bak

Result

input.txt.bak

How It Works

Command Role
grep -l "apple" *.txt Outputs only the names of files containing "apple"
xargs -I {} Passes the file names received via standard input into {} to execute the command
wc -l {} Displays the line count of the target file
cp {} {}.bak Backs up all matched files together

Explanation

By using grep to extract target files and passing the results to xargs, you can run the same operation on all matched files at once.
This combination is efficient even when dealing with a large number of files.

How to Search Multiple Conditions with grep and xargs

Create File

cat << 'EOF' > input.txt ERROR Database connection failed INFO Application started WARN Disk usage is high ERROR Authentication failed INFO Backup completed WARN Memory usage is high ERROR Timeout occurred DEBUG Cache initialized EOF

Command

grep -E 'ERROR|WARN' input.txt | xargs -I {} echo "found:{}"

Result

found:ERROR Database connection failed
found:WARN Disk usage is high
found:ERROR Authentication failed
found:WARN Memory usage is high
found:ERROR Timeout occurred

How It Works

Element Description
grep -E 'ERROR|WARN' Uses extended regular expressions with -E to search for lines matching ERROR or WARN.
xargs Passes each line received via standard input as an argument to the following command.
-I {} Replaces {} with the input line and executes the command.
echo "found:{}" Displays the search results with "found:" prepended.

Explanation

By passing the results matching multiple conditions in grep to xargs, you can format and output each line in any style you like.
Combining it with commands other than echo lets you automate a variety of operations on the search results.

How to Specify Exclusion Conditions with grep and xargs

Create File

cat << 'EOF' > input.txt error: disk full info: process started warning: memory usage high error: permission denied info: backup completed warning: cpu temperature high EOF

Command

grep -v '^info:' input.txt

Result

error: disk full
warning: memory usage high
error: permission denied
warning: cpu temperature high

Command

grep -v '^info:' input.txt | tr '\n' '\0' | xargs -0 -I {} echo "target: {}"

Result

target: error: disk full
target: warning: memory usage high
target: error: permission denied
target: warning: cpu temperature high

How It Works

Item Description
grep -v '^info:' Excludes lines starting with "info:" from the output.
| Passes grep's output to the next command.
-I {} Replaces the received string with {} and executes the command.
echo "target: {}" Displays each remaining line after exclusion as an argument.

Explanation

By using grep to exclude unnecessary lines and passing only the results to xargs, you can run a command exclusively on the data you need.
This combination is commonly used to streamline log analysis and file processing.

How to Handle Filenames Safely with grep and xargs

Create File

cat << 'EOF' > input.txt apple banana target file.txt target.log orange my target data.txt EOF

Command

grep 'target' input.txt

Result

target file.txt
target.log
my target data.txt

Command

grep 'target' input.txt | xargs -I{} printf '[%s]\n' "{}"

Result

[target file.txt]
[target.log]
[my target data.txt]

How It Works

Item Description
grep 'target' Extracts only lines containing "target"
xargs Receives grep's output and passes each line as a command argument one at a time
-I{} Expands the received line into {} and passes it to the command
printf '[%s]\n' "{}" Displays the received string enclosed in [], confirming the passed argument

Explanation

By passing grep's results to xargs, each extracted line can be processed in turn as an argument to another command.
Specifying -I{} expands the entire line into {}, making it easy to pass clearly to the specified command.

How to Handle NULL-Separated Data with grep and xargs

Create File

printf 'apple\0banana split\0orange\0apple pie\0grape\0' > input.txt

Command

grep -z "apple" input.txt | xargs -0 -I{} echo "MATCH: {}"

Result

MATCH: apple
MATCH: apple pie

Command

grep -z "banana" input.txt | xargs -0 -I{} printf '[%s]\n' "{}"

Result

[banana split]

Command

grep -zE "apple|banana" input.txt | xargs -0

Result

apple apple pie banana split

How It Works

Command Description
printf '...\0' > input.txt Creates data separated by NULL characters (\0).
grep -z Treats the input as NULL-separated records and outputs matching records separated by NULL.
grep -zE Uses extended regular expressions to search for multiple patterns.
xargs -0 Safely receives NULL-separated input and passes it to the command as arguments.
xargs -0 -I{} Expands each input into {} and executes the command.

Explanation

Combining grep -z and xargs -0 lets you safely process NULL-separated data. Data containing spaces (such as "banana split" or "apple pie") can be treated as a single record, which is why this combination is often used together with find -print0.

How to Run grep and xargs in Parallel

Create File

cat << 'EOF' > input.txt apple banana grape apple juice orange banana milk apple pie melon EOF

Command

grep "apple" input.txt | tr '\n' '\0' | xargs -0 -P2 -I{} sh -c 'echo "Processing: {}"; sleep 1'

Result

Processing: apple
Processing: apple juice
Processing: apple pie

How It Works

Item Description
grep Extracts lines containing "apple"
tr '\n' '\0' Converts newline separators into NULL character separators, passing them safely to xargs
xargs -0 Receives NULL-character-separated input
-P2 Runs up to 2 processes in parallel
-I{} Expands each received item into {}
sh -c Executes an arbitrary shell command using the expanded data

Explanation

By converting newlines into NULL characters with tr and receiving them with xargs -0, even lines containing spaces can be processed safely.

Specifying -P2 runs up to two processes simultaneously, reducing processing time.

How to Perform Batch Replacement with grep and xargs

Create File

cat << 'EOF' > input.txt apple orange apple juice banana apple pie EOF

Command

grep -l "apple" input.txt | xargs sed 's/apple/APPLE/g'

Result

APPLE
orange
APPLE juice
banana
APPLE pie

How It Works

Command Role
grep -l "apple" input.txt Outputs the name of the file containing "apple"
xargs Passes the file name received via standard input as an argument to the following command
sed 's/apple/APPLE/g' Replaces all occurrences of "apple" with "APPLE" in the target file

Explanation

By using grep to extract only the files matching a condition and passing the results to sed via xargs, you can efficiently perform batch replacement across multiple files.
This method lets you process everything at once without manual work, even when there are many target files.

Efficiently Investigating Log Files with grep and xargs

Create File

cat << 'EOF' > input.txt 2026-07-29 10:00:01 INFO User login successful 2026-07-29 10:01:15 ERROR Database connection failed 2026-07-29 10:02:30 INFO File upload completed 2026-07-29 10:03:45 ERROR Network timeout occurred 2026-07-29 10:04:20 WARN Disk usage high 2026-07-29 10:05:10 ERROR Database query failed EOF

Command

find . -name "*.log" | xargs grep "Database"

Result

./app.log:2026-07-29 10:01:15 ERROR Database connection failed
./app.log:2026-07-29 10:05:10 ERROR Database query failed

Command

find . -name "*.log" | xargs grep -n "ERROR"

Result

./app.log:2:2026-07-29 10:01:15 ERROR Database connection failed
./app.log:4:2026-07-29 10:03:45 ERROR Network timeout occurred
./app.log:6:2026-07-29 10:05:10 ERROR Database query failed

How It Works

Command Role Behavior
grep Keyword search Extracts specified strings from within logs
find File search Retrieves the log files to be investigated
xargs Argument conversion Passes standard input as an argument to commands such as grep
find + xargs + grep Large-scale log investigation Efficiently searches across multiple logs

Explanation

grep is responsible for searching log contents, while xargs efficiently passes the target files to the command.

When investigating a large number of log files, the combination of find | xargs grep is effective.

How to Safely Delete Unnecessary Files with grep and xargs

Create File

mkdir -p work

Create File

touch work/file1.log

Create File

touch work/file2.log

Create File

touch work/file3.txt

Create File

touch work/debug.log

Create File

touch work/readme.md

Command

ls work

Result

debug.log	file1.log	file2.log	file3.txt	readme.md

Command

ls work | grep '.log$' | xargs -r -I {} rm "work/{}"

Result

no output

Command

ls work

Result

file3.txt	readme.md

How It Works

Command Role
ls work Displays the list of files in the directory
grep '\.log$' Extracts only files ending in .log
xargs -r -I {} rm "work/{}" Safely passes the extracted file names to rm for deletion
-r Does not run rm if the input is empty
-I {} Expands the received file name into {}

Explanation

By narrowing down deletion targets with grep and passing only those results to rm via xargs, you can safely delete only the unnecessary files.

Adding -r also prevents unnecessary execution when there are no matching files.

Summary of Key Points for Using grep and xargs

By combining grep and xargs, you can efficiently automate everything from searching to batch processing.

It's important to learn the basics step by step and deepen your understanding by applying them in real-world work.

Leave a Reply

Your email address will not be published. Required fields are marked *

©︎ 2025-2026 running terminal commands