AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-652357

Natasha Shorrock's questions

Martin Hope
Natasha Shorrock
Asked: 2024-12-10 08:24:12 +0800 CST

Tentando classificar com getopts com comandos diferentes e não consigo classificar por preço

  • 5

Estou tentando classificar uma lista de inventário em unix/linux abaixo. Estou conseguindo classificar por nome e ID e consegui abrir o menu de uso, mas não consigo classificar por preço, mesmo com uma função "awk".

Eu chamo o código com ./invOpt -pe a saída continua me dizendo que é um invalid option: -pentão puxa o menu de uso abaixo. Estou confuso porque ele se recusa a classificar o 4º campo onde está o preço. Não sei se o $ e/ou o sinal de vírgula estão bagunçando a classificação

"Usage: invOpts -i | -n | -p | -h
"  -i  sort by product ID"
"  -n  sort by product name"
"  -p  sort by price"
"  -h  display usage"
INVENTORY MENU:
Product ID   Product Name                   Quantity   Price        Total Value
-----------  ------------------------------ --------   -----        -----------
P101        Apple MacBook Pro           25      $2,399.99       $59,999.75
P102        Samsung Galaxy S23          40      $799.99         $31,999.60
P103        Apple iPhone 15             60      $999.99         $59,999.40
P104        Google Pixel 8              35      $899.99         $31,499.65
P105        Microsoft Surface Pro 9     18      $1,299.99       $23,399.82
P106        Dell XPS 13                 50      $1,099.99       $54,999.50
P107        Apple iPad Air              75      $599.99         $44,999.25
P108        Fitbit Charge 5             100     $179.95         $17,995.00
P109        Amazon Echo Dot 5th Gen     150     $49.99          $7,498.50
P110        Sonos One SL                80      $199.99         $15,999.20
P111        Logitech MX Master 3        120     $99.99          $11,998.80
P112        HP Spectre x360             25      $1,499.99       $37,499.75
P113        GoPro Hero 11               60      $399.99         $23,999.40
P114        Nintendo Switch OLED        45      $349.99         $15,749.55
P115        Canon EOS R6                15      $2,499.99       $37,499.85
P116        Seagate 2TB External Hard Drive 200     $69.99          $13,998.00
P117        Apple AirPods Pro 2nd Gen   130     $249.99         $32,498.70
P118        MSI GeForce RTX 4070        40      $599.99         $23,999.60
P119        Lenovo ThinkPad X1 Carbon   20      $1,799.99       $35,999.80
P120        Anker PowerCore 26800       180     $59.99          $10,798.20

CÓDIGO ATUAL:

#!/bin/bash

# Function to display usage information
usage() {
    echo "Usage: invOpts -i | -n | -p | -h"
    echo "  -i  sort by product ID"
    echo "  -n  sort by product name"
    echo "  -p  sort by price"
    echo "  -h  display usage"
}

# Process command-line options using getopts
while getopts ":inp:h" opt; do
    case $opt in
        i)
            # Sort by product ID (Field 1) and save to a temp file
            tempFile="/tmp/inventory_sorted_by_id_$$.txt"
            sort -t: -k1,1 ~/A09/inventory > "$tempFile"
            ;;
        n)
            # Sort by product name (Field 2) and save to a temp file
            tempFile="/tmp/inventory_sorted_by_name_$$.txt"
            sort -t: -k2,2 ~/A09/inventory > "$tempFile"
            ;;
        p)
            # Sort by price (Field 4) and save to a temp file
            tempFile="/tmp/inventory_sorted_by_price_$$.txt"
            sort -t: -k4,4n ~/A09/inventory > "$tempFile"
            ;;
        h)
            # Display usage and exit
            usage
            exit 0
            ;;
        ?)
            # Handle invalid options
            echo "Invalid option: -$OPTARG"
            usage
            exit 1
            ;;
    esac
done

# If no option is provided, default to original file
if [[ -z $tempFile ]]; then
    tempFile=~/A09/inventory
fi

# Source the myFunctions script to use the chkFile function
source ~/Homework9/myFunctions

# Store the inventory file name
filename=~/A09/inventory

# Check if the file exists using chkFile
chkFile $filename
if [[ $? -ne 0 ]]; then
    echo "Error: Inventory file does not exist."
    exit 1
fi

# Print the header
printf "%-12s %-30s %-10s %-15s %-15s\n" "Product ID" "Product Name" "Quantity" "Price" "Total Value"
printf "%-12s %-30s %-10s %-15s %-15s\n" "-----------" "------------------------------" "--------" "-----" "-----------"

# Initialize total inventory value
totalInventoryValue=0

# Read the sorted file line by line (either sorted or original)
while IFS=: read -r productID productName quantity price; do
    # Calculate the total value: Quantity * Price
    totalValue=$(echo "$quantity * $price" | bc -l)

    # Format the price and total value with commas
    formattedPrice=$(echo $price | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta')
    formattedTotalValue=$(echo $totalValue | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta')

    # Print the formatted data
    printf "%-12s %-30s %-10s $%-14s $%-14s\n" "$productID" "$productName" "$quantity" "$formattedPrice" "$formattedTotalValue"

    # Add total value to the overall inventory value
    totalInventoryValue=$(echo "$totalInventoryValue + $totalValue" | bc -l)
done < "$tempFile"

# Format the total inventory value with commas
formattedTotalInventoryValue=$(echo $totalInventoryValue | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta')

# Print the total inventory value
printf "\nTotal Inventory Value: $%-14s\n" "$formattedTotalInventoryValue"

# Clean up the temporary file
rm -f "$tempFile"
linux
  • 1 respostas
  • 13 Views
Martin Hope
Natasha Shorrock
Asked: 2024-09-30 05:15:46 +0800 CST

Tentando classificar em ordem alfabética de sobrenome, mas precisa ser formatado como ID, nome, sobrenome

  • 5

Não importa o que eu tente com cut, awk, sed ou grep, ele ordena primeiro por ID, depois sobrenome e depois primeiro nome, quando deveria ir na ordem do sobrenome, então deveria ficar assim

  f132b02: Kiara Acevedo
  f132a01: Caleb Barn

mas em vez disso ele ordena por ID e não por sobrenome alfabético e a saída fica assim

f132a01: Barn, Caleb
f132b02: Acevedo, Kiara

as informações da pasta que estou recuperando as informações são extraídas de "~/Homework4/etc/passwd" e está tentando ordenar os IDs abaixo

f132a01:Barn  Caleb
f132a02:Casey  Nathan
f132a03:Sanchez  Ana
f132a04:Thomas  Jeff
f132a05:Cavhill  Jared
f132b01:Johnson  Andrew
f132b02:Acevedo  Kiara
f132b03:Felaccio  Steven
f132b05:Blotner  Sam
f132b06:Pereira  Brian

O código que estou testando está abaixo:

ENTRADA:

cut -d: -f1,5 /etc/passwd | grep f132 | \
username, first name, and last name
sed -E 's/(.*), (.*) (.*)/\1 \2 \3/' | \
sort -k3

echo

count=$(cut -d: -f1,5 /etc/passwd | grep f132 | wc -l)
echo "Number of students in the class: $count"

SAÍDA:

    f132a01:Barn  Caleb
    f132a02:Casey  Nathan
    f132a03:Sanchez  Ana
    f132a04:Thomas  Jeff
    f132a05:Cavhill  Jared
    f132b01:Johnson  Andrew
    f132b02:Acevedo  Kiara
    f132b03:Felaccio  Steven
    f132b05:Blotner  Sam
    f132b06:Pereira  Brian
linux
  • 2 respostas
  • 129 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Possível firmware ausente /lib/firmware/i915/* para o módulo i915

    • 3 respostas
  • Marko Smith

    Falha ao buscar o repositório de backports jessie

    • 4 respostas
  • Marko Smith

    Como exportar uma chave privada GPG e uma chave pública para um arquivo

    • 4 respostas
  • Marko Smith

    Como podemos executar um comando armazenado em uma variável?

    • 5 respostas
  • Marko Smith

    Como configurar o systemd-resolved e o systemd-networkd para usar o servidor DNS local para resolver domínios locais e o servidor DNS remoto para domínios remotos?

    • 3 respostas
  • Marko Smith

    apt-get update error no Kali Linux após a atualização do dist [duplicado]

    • 2 respostas
  • Marko Smith

    Como ver as últimas linhas x do log de serviço systemctl

    • 5 respostas
  • Marko Smith

    Nano - pule para o final do arquivo

    • 8 respostas
  • Marko Smith

    erro grub: você precisa carregar o kernel primeiro

    • 4 respostas
  • Marko Smith

    Como baixar o pacote não instalá-lo com o comando apt-get?

    • 7 respostas
  • Martin Hope
    user12345 Falha ao buscar o repositório de backports jessie 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl Por que a maioria dos exemplos do systemd contém WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky Como exportar uma chave privada GPG e uma chave pública para um arquivo 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll status systemctl mostra: "Estado: degradado" 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim Como podemos executar um comando armazenado em uma variável? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S Por que /dev/null é um arquivo? Por que sua função não é implementada como um programa simples? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 Como ver as últimas linhas x do log de serviço systemctl 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - pule para o final do arquivo 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla Por que verdadeiro e falso são tão grandes? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis Substitua a string em um arquivo de texto enorme (70 GB), uma linha 2017-12-30 06:58:33 +0800 CST

Hot tag

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve