Introduction

A TAR (Tape Archive) file is commonly used on Linux and Unix systems to bundle multiple files into a single archive. There may be situations where you need to search for a specific word or string inside the files contained within a TAR archive without manually extracting the entire archive.

The following shell script iterates through each file in a TAR archive, extracts it temporarily, searches for a specified string using grep, displays any matching lines, and restores any existing files with the same name.


Prerequisites

Before running the script, ensure you have:

  • A Linux or Unix-based system.
  • A TAR archive (for example, one.tar).
  • tar and grep utilities installed.
  • Read permission for the archive and write permission in the working directory.
  • Basic knowledge of shell scripting.

Script

search="123"

tar -tf one.tar | while read filename
do
    if [ -f "${filename}" ]
    then
        mv "${filename}" "${filename}.sav"
    fi

    tar -xf one.tar "${filename}"

    found=$(grep -l "${search}" "${filename}")

    if [ ! "${found}X" = "X" ]
    then
        echo "Found \"${search}\" in \"${found}\""
        grep "${search}" "${filename}"
        echo ""
    fi

    if [ -f "${filename}.sav" ]
    then
        mv "${filename}.sav" "${filename}"
    fi
done

How the Script Works

Step 1: Define the Search String

Specify the word or phrase you want to search for.

search="123"

Step 2: List Files in the TAR Archive

The script lists all files contained in the archive.

tar -tf one.tar

Step 3: Preserve Existing Files

If a file with the same name already exists in the current directory, it is renamed with a .sav extension to prevent it from being overwritten.

Step 4: Extract Each File

Each file is extracted individually from the TAR archive.

tar -xf one.tar "${filename}"

Step 5: Search for the Specified Word

The script uses grep to check whether the extracted file contains the search string.

grep -l "${search}" "${filename}"

If a match is found, the filename and matching lines are displayed.

Step 6: Restore Original Files

If a backup file was created, it is restored after the search is completed.


Conclusion

This shell script provides a simple way to search for a specific word or string within files stored in a TAR archive. It extracts files one at a time, searches their contents using grep, and restores any existing files after processing. This approach is useful for inspecting archive contents without manually extracting the entire archive.

Leave a Reply