我正在编写一个bash shell脚本,需要从命令行中获取一个文件:来自
./shell text.txt
text.txt将包含50个单词。每行一个。您必须输出一个新文件,其中包含单词并在每行返回一个。如何对文件进行排序并将其输出到新文件
#!/bin/bash
badchoice () { MSG="Invalid Selection ... Please Try Again" ; }
sort_file() { sort $1 -o sorted_file.txt;}
#---------------------------------
#This stores the unsorted file
#---------------------------------
FILE=""
# Make sure we get file name as command line argument
# Else read it from standard input device
if [ "$1" == "" ]; then
FILE="/dev/stdin"
else
FILE="$1"
# make sure file exist and readable
if [ ! -f $FILE ]; then
echo "$FILE : does not exists"
exit 1
elif [ ! -r $FILE ]; then
echo "$FILE: can not read"
exit 2
fi
fi
# read $FILE using the file descriptors
#----------------------------------
# File input for the first perl script
#----------------------------------
perl_one=""
# Make sure we get file name as command line argument
# Else read it from standard input device
if [ "$2" == "" ]; then
perl_one="/dev/stdin"
else
perl_one="$2"
# make sure file exist and readable
if [ ! -f $perl_one ]; then
echo "$perl_one : does not exists"
exit 1
elif [ ! -r $perl_one ]; then
echo "$perl_one: can not read"
exit 2
fi
fi
# read $perl_one using the file descriptors
#----------------------------------------
# The input for the second perl function
#----------------------------------------
perl_two=""
# Make sure we get file name as command line argument
# Else read it from standard input device
if [ "$3" == "" ]; then
perl_two="/dev/stdin"
else
perl_two="$3"
# make sure file exist and readable
if [ ! -f $perl_two ]; then
echo "$perl_two : does not exists"
exit 1
elif [ ! -r $perl_two ]; then
echo "$perl_two: can not read"
exit 2
fi
fi
# read perl_two using file descriptor
#This is the start of the menu
#---------------------------
# MENU PROMPTS
#---------------------------
menu(){
#clear screen
clear
echo `date`
echo "This is the shell script menu"
echo
echo "A) shell script sort"
echo "B) perl script sort"
echo "C) perl search for a word"
echo
echo "X) To exit the program"
echo
echo $MSG
echo
echo Select by pressing the letter and then ENTER ;
}
while true
do
# 1. display the menu
menu
# 2. read a line of input from the keyboard
read answer
# 3. Clear any error message
MSG=
case $answer in
a|A) sort_file;;
# b|B) bpick;;
# c|C) cpick;;
# Ends the loop
x|X) break;;
# If the entry was invalid call the badchoice function
# to initialize MSG to an error message
*) badchoice;;
esac
# Do it again until the user x
done
答案 0 :(得分:1)
这将是以下几点:
#!/usr/bin/env bash
# Check to ensure exactly one argument passed.
if [[ $# -ne 1 ]] ; then
echo "Usage: shell <inputFile>"
exit 1
fi
# Check that the argument is an existing regular file.
if [[ ! -f $1 ]] ; then
echo "Error: '$1' not a regular file"
exit 1
fi
# Sort it, sending output to xyzzy.new, where xyzzy was the original file.
sort $1 >$1.new
答案 1 :(得分:0)
除了正确引用外,您已经回答了自己的问题:
sort "$1" -o sorted_file.txt
该解决方案有什么问题?