繁体   English   中英

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

[英]Bash Script - getting input from standard input or a file

我有一个bash脚本,该脚本按从命令行获取的名称打印列。 如果我给脚本文件作为参数之一,它将很好地工作。 如果将输入管道输送到脚本并使用/ dev / stdin作为文件,它将无法正常工作。 有谁知道我如何修改脚本以正确接受管道的标准输入? 这是我的剧本。

#!/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;

输入样例:

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 

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

> ./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

来自标准输入的管道(无法正常工作):

> head file1.txt | ./shell_scripts/print_columns.sh /dev/stdin col_1 col_4 col_6 col_2 | head
0185 10215  10195
10136 10166 10186 10146
10137 10167 10187 10147
10138 10168 10188 10148
10139 10169 10189 10149

一个例子:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM