[Bash] Script to swap contents of files

[Bash] Script to swap contents of files

There are two files (for example called „f1” and „f2”). We want to swap contents of these files. Here is an easy bash script, which solves this problem:

# Created by Wojtek Jamrozy (www.wojtekrj.net)
mv $1 cop_$1
mv $2 $1
mv cop_$1 $2

[download id=”8″]
Download this file or make a text file with this content named swap and make it executable with command

chmod +x swap

Then copy this file to /usr/local/bin directory using:

cp swap /usr/local/bin

If you have this file in /usr/local/bin directory (or any other included in $PATH environment variable – command

echo $PATH

will show other directories) you don’t have to write full path to script:

swap f1 f2

will swap contents of files f1 and f2.
Example of usage in shell:

wojtekrj@wojtek-laptop:~$ echo "File 1" > file1 && echo "File 2" > file2
wojtekrj@wojtek-laptop:~$ cat file1
File 1
wojtekrj@wojtek-laptop:~$ cat file2
File 2
wojtekrj@wojtek-laptop:~$ swap file1 file2
wojtekrj@wojtek-laptop:~$ cat file1
File 2
wojtekrj@wojtek-laptop:~$ cat file2
File 1

is a standard header, which helps bash shell recognize file as a bash script.

mv file1 file2

a command, which rename/move file from path file1 to file2

cat file

show content of file

When the script is executed with two arguments (like in example – swap f1 f2), $1 will contain first argument – f1, and $2 second – f2.
When $1 or $2 appears in script, it’s replaced with content of $1 or $2:

mv $1 cop_$1 -> mv f1 cop_f1
mv $2 $1 -> mv f2 f1
echo text_to_display
echo "text_to_display"

commands will show text text_to_display

command > file

will save output of command to file file

3 thoughts on “[Bash] Script to swap contents of files

  1. Hi! I found this off a forum link while googling “bash swap filenames” or similar, and made a few tweaks for my use so I thought I should share:

    # Modified from Wojtek Jamrozy
    # http://www.wojtekrj.net/2008/08/bash-script-to-swap-contents-of-files/
    if [ $# -eq 2 ]
    mv “$1″ tmp$$_”$1”
    mv “$2” “$1″
    mv tmp$$_”$1” “$2”
    echo “$1″ ” “$2”
    echo “Please supply two filenames”


    Require two filenames, mainly because with just one filename, the second and third copies will both fail and your file will be left with the temp name. (If you give it one file that exists and one that dosen’t, it will complain but rename the file anyway)

    Quoted paramaters — because I just spent a whole day tearing my hair out trying to figure out how to robustly deal with e.g. spaces in filenames on unix.

    Verbose output echo line — just my style 🙂

    I wonder if those code tags will work.

    Thanks 🙂

Leave a Reply

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