Batch Work With xargs
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 23 of 39.
xargs reads words from its input and passes them to a command as arguments. It turns a list of paths into one command that works on all of them.
find . -name '*.tmp' -print0 | xargs -0 rmThis deletes every .tmp file below the current folder. Plain xargs splits its input at every space, so old draft.tmp would become two names that do not exist. -print0 makes find end each path with a null character, and xargs -0 splits only there.
echo red green blue | xargs -n 1 echo color:-n 1 passes one argument per command, so this prints color: red, color: green and color: blue on three lines.
ls *.csv | xargs -I {} cp {} {}.bak-I {} runs the command once per input line and puts the line wherever {} stands. With jan.csv and feb.csv, this creates jan.csv.bak and feb.csv.bak.
Challenge
MediumFinish a script that backs up the text files under a folder and counts their lines.
- Open
backup.sh. It already empties thebackupfolder. The folder to back up is its first argument. - Copy every file under that folder whose name ends in
.txtintobackup/, withfind -print0piped intoxargs -0 -I {}. File names may contain spaces. - Print
Copied:, then the output ofls backup. - Print
Lines: N, where N is the total number of lines in those.txtfiles (xargs -0 catpiped intowc -l). - Save the file.
Try it: run bash backup.sh docs. It prints:
Copied:
2024.txt
report.txt
todo.txt
Lines: 6Then run bash backup.sh docs/old: it prints Copied:, 2024.txt and Lines: 1.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter5Text Power Tools
Finding FilesBatch Work With xargsEditing Text With sedColumns With awkRecap - Log SummaryPractice on your own: Terminal playground