Bash脚本 - 从标准输入或文件获取输入

时间:2016-03-09 20:22:17

标签: linux bash

我有一个bash脚本,可以从命令行中按名称打印列。如果我将脚本文件作为参数之一,它就可以正常工作。如果我将输入传递给脚本并使用/ dev / stdin作为文件,它就不能正常工作。有谁知道如何修改脚本以正确接受管道的标准输入?这是我的剧本。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if let grad = self.grads[indexPath.row] {
                self.performSegueWithIdentifier("pushDegree", sender: grad)
        }
    }

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "pushDegree" {
            guard
                let degreeVC = segue.destinationViewController as? DegreeViewController,

            else {
                return
            }
            degreeVC.grad = sender as! Grad
        }

示例输入:

#!/bin/bash

insep=" "
outsep=" "
while [[ ${#} > 0 ]]
do
option="$1"
if [ -f $option ] || [ $option = /dev/stdin ]; 
    then
    break;
fi
case $option in
    -s|--in_separator)
    insep="$2"
    shift # past argument
    shift # past argument
    ;;
    -o|--out_separator)
    outsep="$2"
    shift # past argument
    shift # past argument
    ;;
    *)
         echo "unknown option $option"
         exit 1;
    ;;
esac
done

headers="${@:2}"
grep_headers=$(echo "${headers[@]}" | sed 's/ /|/g')
file=$1

columns=$(awk -F: 'NR==FNR{b[($2)]=tolower($1);next}{print $1,b[$1]}' \
<(head -1 $file | sed "s/$insep/\n/g" | egrep -iwn "$grep_headers" | awk    '{s=tolower($0);print s}') \
<(awk -F: -v header="$headers" 'BEGIN {n=split(tolower(header),a,"  ");for(i=1;i<=n;i++) print a[i]}' $file ) \
| awk '{print "$"$2}' ORS='OFS' | sed "s/OFS\$//")

awk -v insep="$insep" -v outsep="$outsep" "BEGIN{FS=insep;OFS=outsep}{print $columns}" $file

exit;

以file作为参数运行(按预期工作):

col_1 col_2 col_3 col_4 col_5 col_6 col_7 col_8 col_9 col_10
10000 10010 10020 10030 10040 10050 10060 10070 10080 10090
10001 10011 10021 10031 10041 10051 10061 10071 10081 10091
10002 10012 10022 10032 10042 10052 10062 10072 10082 10092
10003 10013 10023 10033 10043 10053 10063 10073 10083 10093
10004 10014 10024 10034 10044 10054 10064 10074 10084 10094
10005 10015 10025 10035 10045 10055 10065 10075 10085 10095
10006 10016 10026 10036 10046 10056 10066 10076 10086 10096
10007 10017 10027 10037 10047 10057 10067 10077 10087 10097
10008 10018 10028 10038 10048 10058 10068 10078 10088 10098 

从标准输入管道(不能按预期工作):

> ./shell_scripts/print_columns.sh file1.txt col_1 col_4 col_6 col_2 | head
col_1 col_4 col_6 col_2
10000 10030 10050 10010
10001 10031 10051 10011
10002 10032 10052 10012
10003 10033 10053 10013

1 个答案:

答案 0 :(得分:2)

一个例子:

script.sh:

#!/bin/bash

if [[ -f "$1" ]]; then
  file="$1"
  cat "$file"
  shift
 else
  while read -r file; do echo "$file"; done
fi
echo "${@}"

测试:

./script.sh file1.txt abc 123 456

UUOC

cat file1.txt | ./script.sh abc 123 456
相关问题