Task 049 .AWK Format

Task 049 .AWK Format

1. Properties of the .AWK File Format

The .AWK file format is a script file used by the AWK text processing utility, which is included with Unix and Linux operating systems. AWK is a programming language designed for pattern scanning and processing of textual data. The .AWK file contains instructions for matching, replacing, and printing text, typically used to generate formatted text or reports. Based on the provided references, the intrinsic properties of the .AWK file format relevant to its file system are:

  • File Extension: .awk
  • Content Type: Plain text, containing AWK programming language instructions.
  • Shebang Line: Typically starts with #!/usr/bin/awk -f to specify the AWK interpreter and indicate that the file is executable.
  • Encoding: ASCII or UTF-8, as AWK scripts are text-based and processed by the AWK utility.
  • Permissions: Often requires executable permissions (e.g., chmod +x script.awk) to run as a standalone script.
  • Structure: Consists of a sequence of patterns and actions, with optional BEGIN and END blocks, and supports AWK-specific syntax (e.g., field variables $1, $2, etc., and built-in variables like FS, RS, OFS).
  • Operating System Compatibility: Primarily supported on Unix and Linux systems; not natively supported on Windows without an AWK interpreter like gawk.
  • File Size: No strict size limit, but typically small as AWK scripts are concise.
  • Purpose: Designed for text manipulation, including matching patterns, replacing text, and formatting output.

These properties are derived from the nature of AWK scripts as described in the references.

2. Python Class for .AWK File

The Python class below handles opening, reading, writing, and printing the properties of an .AWK file. Since AWK files are plain text, the class reads the file content and extracts relevant properties.

import os import stat import magic

class AWKFileHandler:
def init(self, filepath):
self.filepath = filepath
self.properties = {}

def read_file(self):
    """Read the .AWK file and extract its properties."""
    try:
        with open(self.filepath, 'r', encoding='utf-8') as file:
            content = file.read()
            self.properties['file_extension'] = os.path.splitext(self.filepath)[1].lower()
            self.properties['content_type'] = 'text/plain'
            self.properties['shebang'] = content.split('\n')[0] if content.startswith('#!') else 'No shebang'
            self.properties['encoding'] = 'utf-8'  # Assume UTF-8 for text files
            self.properties['permissions'] = oct(stat.S_IMODE(os.stat(self.filepath).st_mode))
            self.properties['structure'] = 'Contains AWK patterns and actions' if '{' in content else 'Empty or invalid AWK script'
            self.properties['os_compatibility'] = 'Unix/Linux'
            self.properties['file_size'] = os.path.getsize(self.filepath)
            self.properties['purpose'] = 'Text manipulation and report generation'
            return content
    except FileNotFoundError:
        raise Exception(f"File {self.filepath} not found")
    except Exception as e:
        raise Exception(f"Error reading file: {str(e)}")

def write_file(self, content):
    """Write content to the .AWK file."""
    try:
        with open(self.filepath, 'w', encoding='utf-8') as file:
            file.write(content)
        # Set executable permissions
        os.chmod(self.filepath, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
        self.read_file()  # Update properties after writing
    except Exception as e:
        raise Exception(f"Error writing file: {str(e)}")

def print_properties(self):
    """Print all properties of the .AWK file."""
    for key, value in self.properties.items():
        print(f"{key.replace('_', ' ').title()}: {value}")

Example usage

if name == "main":
try:
awk_handler = AWKFileHandler("script.awk")
content = awk_handler.read_file()
print("File Content:")
print(content)
awk_handler.print_properties()

    # Example write operation
    sample_content = '#!/usr/bin/awk -f\nBEGIN { print "Hello, AWK!" }'
    awk_handler.write_file(sample_content)
    print("\nAfter writing new content:")
    awk_handler.print_properties()
except Exception as e:
    print(f"Error: {str(e)}")

3. Java Class for .AWK File

The Java class below provides similar functionality to handle .AWK files, reading and writing their content and printing the properties.

import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map;

public class AWKFileHandler {
private String filepath;
private Map<String, String> properties;

public AWKFileHandler(String filepath) {
    this.filepath = filepath;
    this.properties = new HashMap<>();
}

public String readFile() throws IOException {
    Path path = Paths.get(filepath);
    String content = Files.readString(path, StandardCharsets.UTF_8);
    
    properties.put("file_extension", filepath.substring(filepath.lastIndexOf(".")).toLowerCase());
    properties.put("content_type", "text/plain");
    properties.put("shebang", content.startsWith("#!") ? content.split("\n")[0] : "No shebang");
    properties.put("encoding", "UTF-8");
    properties.put("permissions", String.format("0%o", Files.getPosixFilePermissions(path).toArray()));
    properties.put("structure", content.contains("{") ? "Contains AWK patterns and actions" : "Empty or invalid AWK script");
    properties.put("os_compatibility", "Unix/Linux");
    properties.put("file_size", String.valueOf(Files.size(path)));
    properties.put("purpose", "Text manipulation and report generation");

    return content;
}

public void writeFile(String content) throws IOException {
    Path path = Paths.get(filepath);
    Files.writeString(path, content, StandardCharsets.UTF_8);
    // Note: Setting executable permissions is platform-dependent and may require additional libraries
    Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwxr-xr-x"));
    readFile(); // Update properties after writing
}

public void printProperties() {
    for (Map.Entry<String, String> entry : properties.entrySet()) {
        System.out.println(entry.getKey().replace("_", " ").toUpperCase() + ": " + entry.getValue());
    }
}

public static void main(String[] args) {
    try {
        AWKFileHandler handler = new AWKFileHandler("script.awk");
        String content = handler.readFile();
        System.out.println("File Content:");
        System.out.println(content);
        handler.printProperties();

        // Example write operation
        String sampleContent = "#!/usr/bin/awk -f\nBEGIN { print \"Hello, AWK!\" }";
        handler.writeFile(sampleContent);
        System.out.println("\nAfter writing new content:");
        handler.printProperties();
    } catch (IOException e) {
        System.err.println("Error: " + e.getMessage());
    }
}

}

4. JavaScript Class for .AWK File

The JavaScript class below is designed to run in a Node.js environment, as browser-based JavaScript cannot access the file system directly. It handles .AWK file operations and prints properties.

const fs = require('fs').promises; const path = require('path');

class AWKFileHandler {
constructor(filepath) {
this.filepath = filepath;
this.properties = {};
}

async readFile() {
    try {
        const content = await fs.readFile(this.filepath, 'utf-8');
        this.properties.file_extension = path.extname(this.filepath).toLowerCase();
        this.properties.content_type = 'text/plain';
        this.properties.shebang = content.startsWith('#!') ? content.split('\n')[0] : 'No shebang';
        this.properties.encoding = 'utf-8';
        const stats = await fs.stat(this.filepath);
        this.properties.permissions = (stats.mode & 0o777).toString(8);
        this.properties.structure = content.includes('{') ? 'Contains AWK patterns and actions' : 'Empty or invalid AWK script';
        this.properties.os_compatibility = 'Unix/Linux';
        this.properties.file_size = stats.size;
        this.properties.purpose = 'Text manipulation and report generation';
        return content;
    } catch (error) {
        throw new Error(`Error reading file: ${error.message}`);
    }
}

async writeFile(content) {
    try {
        await fs.writeFile(this.filepath, content, 'utf-8');
        await fs.chmod(this.filepath, 0o755); // Set executable permissions
        await this.readFile(); // Update properties after writing
    } catch (error) {
        throw new Error(`Error writing file: ${error.message}`);
    }
}

printProperties() {
    for (const [key, value] of Object.entries(this.properties)) {
        console.log(`${key.replace('_', ' ').toUpperCase()}: ${value}`);
    }
}

}

// Example usage
(async () => {
try {
const handler = new AWKFileHandler('script.awk');
const content = await handler.readFile();
console.log('File Content:');
console.log(content);
handler.printProperties();

    // Example write operation
    const sampleContent = '#!/usr/bin/awk -f\nBEGIN { print "Hello, AWK!" }';
    await handler.writeFile(sampleContent);
    console.log('\nAfter writing new content:');
    handler.printProperties();
} catch (error) {
    console.error(`Error: ${error.message}`);
}

})();

5. C Class for .AWK File

C does not have a direct equivalent to a "class," but we can use a struct and associated functions to achieve similar functionality. The C code below handles .AWK file operations and prints properties.

#include #include #include #include #include

define MAX_LINE 1024

typedef struct {
char* filepath;
char* file_extension;
char* content_type;
char* shebang;
char* encoding;
char* permissions;
char* structure;
char* os_compatibility;
long file_size;
char* purpose;
} AWKFileHandler;

AWKFileHandler* create_handler(const char* filepath) {
AWKFileHandler* handler = (AWKFileHandler*)malloc(sizeof(AWKFileHandler));
handler->filepath = strdup(filepath);
handler->file_extension = NULL;
handler->content_type = NULL;
handler->shebang = NULL;
handler->encoding = NULL;
handler->permissions = NULL;
handler->structure = NULL;
handler->os_compatibility = NULL;
handler->file_size = 0;
handler->purpose = NULL;
return handler;
}

void free_handler(AWKFileHandler* handler) {
free(handler->filepath);
free(handler->file_extension);
free(handler->content_type);
free(handler->shebang);
free(handler->encoding);
free(handler->permissions);
free(handler->structure);
free(handler->os_compatibility);
free(handler->purpose);
free(handler);
}

char* read_file(AWKFileHandler* handler) {
FILE* file = fopen(handler->filepath, "r");
if (!file) {
fprintf(stderr, "Error: Cannot open file %s\n", handler->filepath);
return NULL;
}

fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);

char* content = (char*)malloc(size + 1);
fread(content, 1, size, file);
content[size] = '\0';
fclose(file);

handler->file_extension = strdup(strrchr(handler->filepath, '.') ? strrchr(handler->filepath, '.') : ".awk");
handler->content_type = strdup("text/plain");
handler->shebang = content[0] == '#' && content[1] == '!' ? 
                  strdup(strtok(strdup(content), "\n")) : strdup("No shebang");
handler->encoding = strdup("utf-8");

struct stat st;
stat(handler->filepath, &st);
char perm[10];
snprintf(perm, sizeof(perm), "%o", st.st_mode & 0777);
handler->permissions = strdup(perm);
handler->structure = strstr(content, "{") ? 
                     strdup("Contains AWK patterns and actions") : strdup("Empty or invalid AWK script");
handler->os_compatibility = strdup("Unix/Linux");
handler->file_size = size;
handler->purpose = strdup("Text manipulation and report generation");

return content;

}

int write_file(AWKFileHandler* handler, const char* content) {
FILE* file = fopen(handler->filepath, "w");
if (!file) {
fprintf(stderr, "Error: Cannot write to file %s\n", handler->filepath);
return -1;
}
fputs(content, file);
fclose(file);

chmod(handler->filepath, 0755); // Set executable permissions
free_handler(handler);
handler = create_handler(handler->filepath);
read_file(handler); // Update properties
return 0;

}

void print_properties(AWKFileHandler* handler) {
printf("File Extension: %s\n", handler->file_extension);
printf("Content Type: %s\n", handler->content_type);
printf("Shebang: %s\n", handler->shebang);
printf("Encoding: %s\n", handler->encoding);
printf("Permissions: %s\n", handler->permissions);
printf("Structure: %s\n", handler->structure);
printf("OS Compatibility: %s\n", handler->os_compatibility);
printf("File Size: %ld\n", handler->file_size);
printf("Purpose: %s\n", handler->purpose);
}

int main() {
AWKFileHandler* handler = create_handler("script.awk");
char* content = read_file(handler);
if (content) {
printf("File Content:\n%s\n", content);
print_properties(handler);

    const char* sample_content = "#!/usr/bin/awk -f\nBEGIN { print \"Hello, AWK!\" }";
    if (write_file(handler, sample_content) == 0) {
        printf("\nAfter writing new content:\n");
        print_properties(handler);
    }
    free(content);
}
free_handler(handler);
return 0;

}

Notes

  • File System Access: The JavaScript and C implementations assume a Unix-like environment for file system operations and permissions handling. Java’s file permission setting is limited without additional libraries, so it may not work on all platforms.
  • AWK File Structure: The classes check for the presence of { to determine if the file contains valid AWK patterns, as this is a common feature of AWK scripts.
  • Error Handling: Each class includes basic error handling for file operations.
  • Permissions: Executable permissions are set where possible, as AWK scripts often require this to run as standalone scripts.

These implementations provide a robust way to handle .AWK files across different programming languages while adhering to the specified requirements.