如何在自定义 bash 脚本中使用不同命令的管道输出?

如何在自定义 bash 脚本中使用不同命令的管道输出?

我有这个简单的脚本:

#!/bin/bash

# This command removes the last "\n" (line feed) character from the file specified as parameter
#
# Params:
# $1 [FILE_NAME] - the name of the file to trim

if [ "$1" = "" ]; then
        echo "perlrmlastlf - A command utility which uses perl to remove the last \"\n\" (line feed) character inside a file"
        echo $'\r'
        echo "perlrmlastlf: missing FILE_NAME"
        echo "Usage: perlrmlastlf [FILE_NAME]"
        echo $'\r'
        exit;
fi

if [[ ! -f $1 ]]; then
        echo "perlrmlastlf - A command utility which uses perl to remove the last \"\n\" (line feed) character inside a file"
        echo $'\r'
        echo "perlrmlastlf: wrong FILE_NAME $1: No such file"
        echo "Usage: perlrmlastlf [FILE_NAME]"
        echo $'\r'
        exit;
fi

FILE=$1
TMP_FILE="$FILE.tmp.perlrmlastlf"
perl -0 -pe 's/\n\Z//' $FILE > $TMP_FILE

mv $TMP_FILE $FILE

现在,我实际上只能使用有效的文件名作为参数,但如果我想让它从管道接收输出并使用它而不是 $1 [FILE_NAME] 怎么办?像这样:

user:machine ~$ cat file.txt | pcregrep -o "some pattern" | perlrmlastlf
user:machine ~$ # output of `cat file.txt | pcregrep -o "some pattern"` but without last \n, if present

perlrmlastlf接收管道输出并使用它,然后将匹配的字符串(不带最后一个 \n 字符)输出回控制台

我怎样才能做到这一点?

答案1

我确信有更优雅的方法,但现在还为时过早......

if (( $# > 0 )); then
    # the "-i" option takes care of writing to a tmp file and 
    # overwriting the original file
    perl -0 -i -pe 's/\n\Z//' "$1"
else
    # read from stdin and write to stdout
    perl -0 -pe 's/\n\Z//'
fi

您需要删除该[[ $1 == "" ]]检查,然后将该[[ ! -f $1 ]]检查放入我的 if 语句的“true”块中。

相关内容